Why does Array (n) .forEach loop n times?

Array(3)gives [ , , ]which has lengthof 3.

[1, 2, 3].forEach loops 3 times as expected.

However Array(3).forEach, [ , , ].forEachloops in general.

Why is this? I thought I discovered a way to do something nonce without using loops for, and I'm disappointed that it doesn't work!

+4
source share
1 answer

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

Example from MDN:

Fiddle

function logArrayElements(element, index, array) {
  console.log('a[' + index + '] = ' + element);
}

// Notice that index 2 is skipped since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9

Take a look at the MDN article.

.

+2

All Articles