Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
22
rated 0 times [  23] [ 1]  / answers: 1 / hits: 55811  / 11 Years ago, sat, april 6, 2013, 12:00:00

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?


More From » arrays

 Answers
15

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

[#79089] Thursday, April 4, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
victorr

Total Points: 193
Total Questions: 86
Total Answers: 105

Location: Pitcairn Islands
Member since Thu, Jun 24, 2021
3 Years ago
victorr questions
Fri, Nov 13, 20, 00:00, 4 Years ago
Sat, Jul 25, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;