After reading this SO Question, I'm still a little confused as to what Array.apply is actually doing. Consider the following snippet:
new Array(5).map(function(){
return new Array(5);
});
I expect this to init an array with 5 undefined entries, then map over them creating a two dimensional array of 5x5);
Instead I just get the array as if it was never mapped over:
[undefined, undefined, undefined, undefined, undefined]
When I wrap the constructor call to array in an Array.apply call, then map over that, it works as expected:
Array.apply(null, new Array(5)).map(function(){
return new Array(5);
});
resulting in;
[[undefined, undefined, undefined, undefined, undefined],
[undefined, undefined, undefined, undefined, undefined],
[undefined, undefined, undefined, undefined, undefined],
[undefined, undefined, undefined, undefined, undefined],
[undefined, undefined, undefined, undefined, undefined]];
What's the deal? Is Array.apply just another way of calling new Array(), or Array.prototype.constructor? Are there any other situations where this would be advantageous? Also, why didn't my first approach pick up on the map I was sending it through?
Thanks!
-Neil
See Question&Answers more detail:
os