ForEach does not work when for loop works with an array of objects

I have such an array

var updates = [];

Then I add material to an array like this

updates["func1"] = function () { x += 5 };

When I call functions with a for loop, it works as expected

for(var update in updates) {
     updates[update]();
}

But when I use forEach, it does not work !?

updates.forEach(function (update) {

    update();
});

forEach definitely works in my browser, which is google chrome, what am I doing wrong?

+5
source share
2 answers

forEach iterates indexesno more properties. Your code:

updates["func1"] = "something";

Adds a property to the object - this, by the way, is an array - not an element of the array. In fact, this is equivalent to:

updates.func1 = "something";

If you need something like a hash map, you can use a simple object instead:

updates = {};

updates["func1"] = "something";

for…in,

Object.keys :

Object.keys(updates).forEach(function(key) {
    console.log(key);
}); 
+9

, . for .. in , forEach .

, :

updates.push(function () { x += 5 });

, , , :

var updates = {}

for ... in.

+5

All Articles