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?
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!
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
JavaScript's Array#forEach() function lets you iterate over an array, but not over an object.
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With