The following Javascript function returns a JS object:
function getCookies() {
var result = {};
var cookie = {};
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
cookie = cookies[i].split('=');
result[cookie[0]] = cookie[1];
}
return result;
}
When I tried to access its fields the "easy" way, all I got was "undefined", eg:
var c = getCookies();
alert(c.a_cookie_name);
alert(c['a_cookie_name']);
The only way I could access the keys and values was iterating through the fields, eg:
for(cookieName in c){
alert(c[cookieName]);
}
The question is how to access the fields without iterating?
Thank you.
P.S. The keys and values do exist, I can see the object fields with console.log(getCookies()) in Chrome.
You are properly accessing fields the problem is that hte fields you're accessing don't exist. It' looks like the property named a_cookie_name simply doesn't exist on the object.
EDIT
Given that the Chrome console shows the properties as existing, one possibility to consider is there is white space in the names of the properties. This could explain the difference as the white space would be hard to see in the console. To test that out try the following. It will make the spaces a bit more visible if they are there
for (var cookieName in c) {
alert('"' + cookieName + '"="' + c[cookieName] + '"');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With