0

I just want to know why forEach doesn't work on an associative array:

var array =[];
array['W'] = 0;
array['S'] = 1;

// This doesn't work
console.log(array);
array.forEach(function(item){
console.log(item);
});

// This does
for(var key in array){
console.log(array[key]);
}
2
  • You are using an array like an object. Arrays are objects, but they're not used like that. var array = []; should be var object = {};, then it will become clear. Commented Dec 15, 2017 at 0:15
  • if i change array to var array ={}; it'd throw a not a function error on the forEach function as it only runs on arrays. Commented Dec 15, 2017 at 0:20

2 Answers 2

3

Array.prototype.forEach is defined by the standard to iterate over index members.

for-in enumerates all object properties.

So in short, the answer to your "why" question is: because the standard says so.

Sign up to request clarification or add additional context in comments.

Comments

1

Probably because array.length evaluates to 0. You could use Object.values(array).forEach to iterate over the actual values of the array.

2 Comments

You're right this works: Object.values(array).forEach(function(item){ console.log('2',item); });
@NaguibIhab If you are using Object.values then you might as well change var array = [] to var object = {}.

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.