Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 534
GriffLab Avatar asked Apr 06 '13 02:04

GriffLab


People also ask

Why is my forEach not working?

The "forEach is not a function" error occurs when we call the forEach() method on a value that is not of type array, Map , or Set . To solve the error, make sure to only call the forEach method on arrays, Map or Set objects. Copied!

Can you use a forEach loop on an array?

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Does forEach work on objects?

JavaScript's Array#forEach() function lets you iterate over an array, but not over an object.

Is JavaScript forEach blocking?

forEach Asynchronous? It is not asynchronous. It is blocking. Those who first learned a language like Java, C, or Python before they try JS will get confused when they try to put an arbitrary delay or an API call in their loop body.


1 Answers

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);
}); 
like image 200
ZER0 Avatar answered Sep 25 '22 12:09

ZER0