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?
asked Mar 11, 2013 at 1:15
hAlE
1,2933 gold badges13 silver badges19 bronze badges
2 Answers 2
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]`
}
}
answered Mar 11, 2013 at 1:18
Explosion Pills
192k56 gold badges341 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
hugomg
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.Explosion Pills
@missingno why would someone do such a thing??
scott.korin
if the for loop is on the keys in the object, why is the check for hasOwnProperty necessary?
hugomg
@ExplosionPills: The key names might have come from an external source. Its just some defensive programming.
Guffa
@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.
|
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.
answered Mar 11, 2013 at 1:17
Ben McCormick
25.8k12 gold badges56 silver badges71 bronze badges
Comments
lang-js
var o = {a:1,b:2,c:3}, thenfor..into loop.