tags:

views:

27

answers:

3

This is trivial I know but I'm so used to OOP languages. I'm trying to figure out how to write out each name/value in either one alert or many, just so I can verify the data

var dCookieNameValuePairs = {};

for (i = 0; i < cookieValues.length; i++)
{
    var akeyValuePair = aCookieValues[i].split("=");
    dCookieNameValuePairs[keyValuePair[0]] = keyValuePair[1];
}

// display each name value pair testing
for (i = 0; i < dCookieNameValuePairs.length; i++)
{
    alert("Name: " + dCookieNameValuePairs[] + "Value: " + 
}

I'm stuck at the second for loop...I am not sure how to iterate through the dictionary and then focus on each name/value to spit it back.

+1  A: 

You want to use for..in for enumerating through a dictionary/map.

for ( var prop in dCookieNameValuePairs ) {
   if ( dCookieNameValuePairs.hasOwnProperty( prop ) ) {
       alert( dCookieNameValuePairs[prop] )
   }
}

I may have typo'd. Only use .length when you are dealing with an array [] or a custom array-like object that you defined to have .length populated.

meder
Thanks, I haven't use much JS so really never used a for loop in JS yet. Makes sense now.
CoffeeAddict
A: 

The object dCookieNameValuePairs that you've created in the first loop is functioning as an associative array; that is to say, each item in it has a key (name) and a value. It doesn't have a numerical index like a regular array would.

Therefore you want to loop through the keys and, for each one, print out the key and the value:

for (var propKey in dCookieNameValuePairs) {
    if (dCookieNameValuePairs.hasOwnProperty(propKey)) {
         alert("Name:" + propKey + " Value:" + dCookieNameValuePairs[propKey]);
    }
}

Note the "hasOwnProperty" call: when you use "in" to iterate over the properties of an object, you will get properties (such as "length") that you didn't put in yourself -- your object inherits them. The "hasOwnProperty" call means that you only get back the properties you put in.

JacobM
A: 
for (i in dCookieNameValuePairs) {
    alert("Name: " + i + " Value: " + dCookieValuePairs[i]);
}

See the "JavaScript Does Not Support Associative Arrays" section of this page for more details.

If you don't need an associative array, you might put the keys and values into an array of objects instead. So your first loop would look something like this:

for (i = 0; i < cookieValues.length; i++) {
    var akeyValuePair = cookieValues[i].split("=");
    dCookieNameValuePairs.push({key: akeyValuePair[0], value: akeyValuePair[1]});
}
Daren