I am currently using two kinds of iterations in my code:
For objects (snippet 1):
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
// do stuff with key and obj[key]
}
}
For arrays (snippet 2):
for (var i=0, count=arr.length;i<count;i++) {
// do stuff with i and arr[i]
}
I’d like to simplify my code and use a single function for both objects and arrays (snippet 3):
var keys=Object.keys(arrorobj);
for (var i=0, count=keys.length;i<count;i++) {
// do stuff with keys[i] and arrorobj[keys[i]]
}
I know that the snippet 3 is fine for objects, but is it also going to work as I expect with arrays, and replace both snippets 1 and 2? In particular, can I be assured that in all browsers (well, at least those that support Object.keys) snippet 3 will respect the key order (up from index 0)?
[edit] I plan to use this in particular for deep merge of objects. My current code is heavy as at each level I have 3 branches depending on the type (array, object or other).
It will work while the only enumerable properties on your array are the numbered slots (the default of an
Array), but it doesn’t make a guarantee of the ordering of the returned properties, as they’re defined to be infor ( in )order, which doesn’t always iterate numerically (depending on how the properties were assigned).If you assigned another property, it’d also be enumerated (this wouldn’t happen with a more standard iteration technique).
It also wouldn’t behave quite the same for empty slots (e.g.
new Array(25)), as theforloop would iterate over these.It is generally recommended to use a
forloop for an Array, orforEach()method (or related).