1

I got a problem when I was using the Array.prototype.forEach function.

here is my code, I'm wondering why the forEach function doesn't execute any loop step when an array is created by the Array constructor without initial value

var arr = new Array(3) //arr : [undefined, undefined, undefined]
arr.forEach(function(){
    console.log('my code');
})//doesn't output the expected result

//this works well
for(var i = 0, length = arr.length; i < length; i++)
    console.log('output the expected result')

//this case works well too.
var arr2 = new Array(undefined, undefined, undefined)   // arr2: [undefined, undefined, undefined]

arr2.forEach(function(){
    console.log('my code');
})//works well
Deryckxie
  • 355
  • 1
  • 3
  • 9

1 Answers1

3

From the documentation (please note the bold part):

forEach() executes the provided callback once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialised (i.e. on sparse arrays).

So the behaviour of your application is correct.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56