Reputation: 2166
I have an array like so
var updates = [];
I then add stuff to the array like this
updates["func1"] = function () { x += 5 };
When I call the functions with a for loop it works as expected
for(var update in updates) {
updates[update]();
}
But when I use the forEach it doesn't work!?
updates.forEach(function (update) {
update();
});
forEach definitely works in my browser which is google chrome, what am I doing wrong?
Upvotes: 18
Views: 65246
Reputation: 25322
forEach iterates over indexes
not over properties
. Your code:
updates["func1"] = "something";
Adds a property to an object – that incidentally is an array – not an element to an array. In fact, it's equivalent to:
updates.func1 = "something";
If you need something like an hashmap, then you can use a plain object instead:
updates = {};
updates["func1"] = "something";
And then iterate using for…in
, that shouldn't be used on arrays
Or you can use Object.keys to retrieve the properties an iterate over them:
Object.keys(updates).forEach(function(key) {
console.log(key);
});
Upvotes: 30
Reputation: 78640
You aren't adding the items to the array, you are adding object properties to your array object. for .. in
will return all properties, forEach
only iterates over array elements.
To add to the array, you would do this:
updates.push(function () { x += 5 });
If you intend to add in the way you are, then just use an object and not an array:
var updates = {}
and then use for ... in
.
Upvotes: 6