18

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?

2 Answers 2

30

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);
}); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this helped me understand it alot better, I read I should not have used for...in which is why I asked the question, so thanks for the alternative to for...in :)
6

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.