Initializing an array with values
It is not a frequent use case, but it comes up occasionally: Producing an array [1] of a given length that is filled with values. This blog post explains how to do it and what to watch out for. Let us start with something simple: producing an array of length n whose first element is 0, second element is 1, etc. Array.prototype.map() Once you have an array with length n , you can use the array method map() to fill it appropriately. For example, to produce the array [0, 1, 2] , any array of length 3 will do: > var arr = [null, null, null]; > arr.map(function (x, i) { return i }) [ 0, 1, 2 ] Alas, map() skips holes, but preserves them [2] , which is why an empty array (with only holes) does not work for us: > new Array(3).map(function (x, i) { return i }) [ , , ] The next two sections look at ways of creating an array with a given length. Filling an array via apply() Function.prototype.apply() treats holes as if they were undefined elements [3] . Theref...