-2

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?

angry kiwi
  • 10,730
  • 26
  • 115
  • 161

3 Answers3

2

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.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • I checked out set, it's not full supported yet at this moment. – angry kiwi Apr 08 '16 at 11:26
  • If the browser you're targeting don't support it, then use a simple object instead of an array. Or use push to add elements. – Denys Séguret Apr 08 '16 at 11:27
  • can you please elaborate why it breaks optimization? – angry kiwi Apr 08 '16 at 11:28
  • Array manipulation are very fast in moderne JS engines when the array is used in an expected way. You can see an introduction to this problem here: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers (with exemples less basic than just making an array not an array) – Denys Séguret Apr 08 '16 at 11:32
2

Because that's not how you add a value to a javascript array. You have to use the method Array.prototype.push()

var list = ['lemon', 'apple'];
list.push('durian');

list.forEach(function(i){
    console.log(i);
});
Vitor Rigoni
  • 573
  • 4
  • 14
1

list['yuck'] = 'durian';

Here the syntax says add the text durain to a property yuck.

Here you are adding key values. This is how you assign values to a object.

The above line will throw an exception as you cannot add key values to array. So your array is never modified.

And this one

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

You are looping the initial array. Hence same values are printed.

On other hand you can use. list.push('durian')

Or

list[2] = 'durian'

Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59