node icon indicating copy to clipboard operation
node copied to clipboard

Array.prototype.map not loops over "virtual" undefined elements

Open andreytkachenko opened this issue 10 years ago • 1 comments

Here is an example

let arr = [];
arr[12] = 1;
let arr2 = arr.map( i => 0 );

we will have in arr2 = [ undefined x 12, 0 ]; but actually expected [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

andreytkachenko avatar Dec 18 '15 14:12 andreytkachenko

Indeed! Check out the specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map especially this part:

map calls a provided callback function once for each element in an array, 
in order, and constructs a new array from the results. callback is invoked 
only for indexes of the array which have assigned values, including undefined. 
It is not called for missing elements of the array (that is, indexes that have 
never been set, which have been deleted or which have never been assigned a value).

The last sentence applies to the first 12 positions in your array.

davidvgalbraith avatar Dec 18 '15 14:12 davidvgalbraith