0

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?

2
  • This is not really an array, at least not in the sense you expect it to be... Commented Mar 11, 2013 at 1:16
  • An object is what you need here... var o = {a:1,b:2,c:3}, then for..in to loop. Commented Mar 11, 2013 at 1:17

2 Answers 2

5

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]`
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

I prefer using Object.prototype.hasOwnProperty.call(obj, key) so I don't need to worry about someone using 'hasOwnProperty as a key and shadowing the method.
@missingno why would someone do such a thing??
if the for loop is on the keys in the object, why is the check for hasOwnProperty necessary?
@ExplosionPills: The key names might have come from an external source. Its just some defensive programming.
@scott.korin: In this case it's not, but if it would be an object that has methods in its prototype, it keeps the methods from showing up as properties.
|
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.