I recently discovered the following snippet of code on SO to aid in quickly populating an array with default values:
Array.apply(null, new Array(3)).map(function() {return 0;});
Given the behavior of the Array constructor and the apply method, the above snippet can also be rewritten as such:
Array.apply(null, [undefined, undefined, undefined]).map(function() {return 0;});
This technique is also useful when dealing with sparse arrays that you wish to populate with default values:
var sparseArr = [3,,,4,1,,],
denseArr = Array.apply(null, sparseArr).map(function(e) {
return e === undefined ? 0 : e;
});
// denseArr = [3,0,0,4,1,0]
However it is therein that two oddities arise:
- If the final term of of
sparseArr
is undefined, that term is not mapped indenseArr
- If
sparseArr
contains only a single term (e.g.sparseArr = [1]
) or a single term followed by a single trailing undefined term (e.g.sparseArr = [1,]
), the resultingdenseArr
equals[undefined x 1]
Can anyone explain this behavior?