Reputation: 3925
I thought I solved my problem using the for (var key in arr) suggested here but this causes trouble in IE. Now I am back to square one.
var myVariable = [];
myVariable['option-1'] = 'something';
myVariable['option-2'] = 'something else';
$.each(myVariable, function(index, value) {
alert(index + ': ' + value);
});
It doesn't work. Nothing shows. Can someone edit it to make it work?
Upvotes: 0
Views: 93
Reputation: 664548
Instead, use an object literal:
var myVariable = {};
// ^^
myVariable['option-1'] = 'something';
…
Upvotes: 1
Reputation: 8852
myVariable
is an array. To add things to an array you use myVariable.push('something')
. You are using square bracket syntax, which is how you would normally add properties to an object.
Since arrays are objects, you can still access option-1
, but it is not a member of the array, it is a property of the object: myVariable['option-1']; // "something"
The solution is to set myVariable
to an object. jQuery's each
method will iterate over the properties of the object as expected.
Upvotes: 2
Reputation: 11820
Change var myVariable = [];
to var myVariable = {};
.
The syntax that you're using, myVariable['option-1'] = 'something';
is for objects, not arrays.
Upvotes: 3
Reputation: 146310
No need for jQuery.
Just use a for..in
loop (with an object {}
not an array []
):
for(var index in myVariable) {
var value = myVariable[index];
alert(index + ': ' + value);
}
Upvotes: 1