RST
RST

Reputation: 3925

Object, Array and $.each()

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

Answers (5)

Bergi
Bergi

Reputation: 664548

There are no associative arrays in JavaScript, and non-numeric properties on arrays are bad practise!.

Instead, use an object literal:

var myVariable = {};
//               ^^

myVariable['option-1'] = 'something';
…

Upvotes: 1

Rick Viscomi
Rick Viscomi

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

sbeliv01
sbeliv01

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

bfavaretto
bfavaretto

Reputation: 71918

Just use an object instead of an array:

var myVariable = {};

Upvotes: 4

Naftali
Naftali

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

Related Questions