angry_kiwi angry_kiwi - 4 months ago 10
Javascript Question

It is possible to assign array 'value key' to a value?

I have an array like this

var list =['lemon', 'apple'];
list['yuck'] = 'durian';

list.forEach(function(i){
console.log(i);
});


The out put is

lemon
apple


So where is durian?

This question is not about how use array properly, I just find it odd that we able to do that, what's really going on here?

Answer

forEach iterates on an array's elements, that is the properties identified by a positive integer. 'yuck' is a string which can't be converted to an integer.

If you really want to iterate on all values, you can do this:

for (var key in list) {
  console.log(list[key]);
}

But it breaks all the optimizations of arrays. You should probably use a Set or an object instead.