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
0

1 Answer 1

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.

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

2 Comments

thank you very much, I just ignored this important line before.
If you think that this is the right answer you can check it with the green flag. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.