javascript - forEach not working when for loop does with an array of objects -
i have array so
var updates = []; i add stuff array this
updates["func1"] = function () { x += 5 }; when call functions loop works expected
for(var update in updates) { updates[update](); } but when use foreach doesn't work!?
updates.foreach(function (update) { update(); }); foreach works in browser google chrome, doing wrong?
foreach iterates on indexes not on properties. code:
updates["func1"] = "something"; adds property object – incidentally array – not element array. in fact, it's equivalent to:
updates.func1 = "something"; if need hashmap, can use plain object instead:
updates = {}; updates["func1"] = "something"; and iterate using for…in, shouldn't used on arrays
or can use object.keys retrieve properties iterate on them:
object.keys(updates).foreach(function(key) { console.log(key); });
Comments
Post a Comment