var hello = Array.apply(null, Array(5)).map(function (x, i) { return i; });
I get what map does, but I don't understand why the function does what it does to make the hello == [0, 1, 2, 3, 4]
var hello = Array.apply(null, Array(5)).map(function (x, i) { return i; });
I get what map does, but I don't understand why the function does what it does to make the hello == [0, 1, 2, 3, 4]
The second parameter on the closure passed to map
is the array key. That is what is being returned so you're getting 5 array keys, starting at 0.
Maybe we should break it down:
var arr = Array(5);
arr === [,,,,,]; // array with five undefined slots
arr === [undefined, undefined, undefined, undefined, undefined]; // same as this :)
Each has an index:
arr[4]; // yay! => undefined
map
loops through each slot and the mapping function gets 2 params, the value and the index.
function (x, i) { return i; }
map
produces an array of all the return
values from the mapping function.
You can find out by performing a dry run of your code:
var hello = Array.apply(null, Array(5))
At this point:
hello == [undefined,undefined,undefined,undefined,undefined]
Now:
hello.map(function (x, i) { return i; });
Is the equivalent to (use the comments to see how the below references the above function:
for(var i = 0; i < hello.length; i++){ // i is the index
x = hello[i]; // x is the value at each index
// Function body below using `hello[i] = ` instead of return
hello[i] = i;
}
Hence the result from setting each element in the list to the index of that element:
[0, 1, 2, 3, 4]