hAlE
hAlE

Reputation: 1293

iterating an array indexed by strings in Javascript

I have an array in which I use strings as indexes of my array. Suppose I have:

var array = [];
array["a"] = 1;
array["b"] = 2;
array["c"] = 33;

how can I iterate in "array" to show all of its element?

Upvotes: 0

Views: 80

Answers (2)

Ben McCormick
Ben McCormick

Reputation: 25728

An "array" with string indices is not an array at all in JS, but an object with properties. You want:

var obj = {
  a:1,
  b:2,
  c:33
};


for (var prop in obj){
  //this iterates over the properties of obj, 
  //and you can then access the values with obj[prop]
  if (obj.hasOwnProperty(prop)) {
    doSomething(obj[prop]);
  }
}

Arrays only have indices that can be parsed as integers.

Upvotes: 3

Explosion Pills
Explosion Pills

Reputation: 191749

Arrays in JS can only have ordinal numeric keys, but objects can have strings as keys. You can't iterate over them per se since the keys are not ordinal, but you can show all elements:

var obj = {};
obj['a'] = 1;
obj['b'] = 2;
/* alternatively */ var obj = {'a': 1, 'b': 2};

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        //access via `obj[key]`
    }
}

Upvotes: 5

Related Questions