Skip to content
Advertisement

Mapping Array in Javascript with sequential numbers

The following code:

let myArray = Array.apply(null, {length: 10}).map(Number.call, Number);

Creates the following Array:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

I just don’t understand why. I can’t find anything on the internet that explains this behavior. Does anyone know why this works the way it does? Perhaps a link to some documentation?

Advertisement

Answer

Array.apply(null, {length: 10})

creates an array of length 10 with all elements being undefined.

.map(Number.call, Number)

will invoke Number.call for each element with the arguments (element, index, array) and setting this to Number. The first argument to call will be taken as this (not relevant here), and all the other arguments are passed as they are, with the first one being the index. And Number will now convert its first argument, index, to a number (here: will return the index, as it is a number), and that’s what map will write to its return array.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement