简体   繁体   中英

forEach not working when for loop does with an array of objects

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?

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);
}); 

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM