Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript Array map with apply

I am trying to declare and initialize an array with 0, in javascript. I created an array and set the length like this.

var previousRow = [];
previousRow.length = 5;

Then, I did this.

console.log(previousRow);
previousRow = previousRow.map(Number.prototype.valueOf, 0);
console.log(previousRow);

and I got,

[ , , , ,  ]
[ , , , ,  ]

But, when I did

console.log(previousRow);
previousRow = Array.apply(null, previousRow).map(Number.prototype.valueOf, 0);
console.log(previousRow);

I got what I expected

[ , , , ,  ]
[ 0, 0, 0, 0, 0 ]

Why the first code didn't work?

like image 537
thefourtheye Avatar asked Sep 28 '13 08:09

thefourtheye


1 Answers

Read the MDN documentation for map. It clearly states:

callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

The previousRow array is an empty array of length 5. However the elements have never been assigned a value:

var previousRow = [];
previousRow.length = 5;

Since the elements of previousRow have never been assigned a value they will never be processed by map. Hence mapping Number.prototype.valueOf over previousRow will result in an empty array of 5 elements:

console.log(previousRow);
previousRow = previousRow.map(Number.prototype.valueOf, 0);
console.log(previousRow);

However when you apply previousRow to the Array constructor the constructor creates a new array and assigns the values of previousRow to the new array.

It doesn't matter whether the elements of previousRow were assigned a value. When JavaScript can't find a value it supplies undefined instead.

Hence the net effect is that the new array has 5 elements all of which are assigned undefined explicitly by the Array constructor. Hence you can use map to process the entire array:

console.log(previousRow);
previousRow = Array.apply(null, previousRow).map(Number.prototype.valueOf, 0);
console.log(previousRow);

You should read the following answer for a more in depth explanation: https://stackoverflow.com/a/18949651/783743

like image 111
Aadit M Shah Avatar answered Sep 20 '22 06:09

Aadit M Shah