Is there a more compact way to do this sort of initialization?
for (var i = 0; i < arraySize; i++) array[i] = value;
The OP seems to be after compactness in a single-use scenario over efficiency and re-usability. For others looking for efficiency, here's an optimization that hasn't been mentioned yet. Since you know the length of the array in advance, go ahead and set it before assigning the values. Otherwise, the array's going to be repeatedly resized on the fly -- not ideal!
function initArray(length, value) {
var arr = [], i = 0;
arr.length = length;
while (i < length) { arr[i++] = value; }
return arr;
}
var data = initArray(1000000, false);
This is not likely to be better than any of the techniques above but it's fun...
var a = new Array(10).join('0').split('').map(function(e) {return parseInt(e, 10);})
Stumbled across this one while exploring array methods on a plane.. ohhh the places we go when we are bored. :)
var initializedArray = new Array(30).join(null).split(null).map(function(item, index){
return index;
});
.map()
and null
for the win! I like null because passing in a string like up top with '0' or any other value is confusing. I think this is more explicit that we are doing something different.
Note that .map()
skips non-initialized values. This is why new Array(30).map(function(item, index){return index});
does not work. The new .fill()
method is preferred if available, however browser support should be noted as of 8/23/2015.
Desktop (Basic support)
From MDN:
[1, 2, 3].fill(4); // [4, 4, 4]
[1, 2, 3].fill(4, 1); // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2); // [1, 4, 3]
[1, 2, 3].fill(4, 1, 1); // [1, 2, 3]
[1, 2, 3].fill(4, -3, -2); // [4, 2, 3]
[1, 2, 3].fill(4, NaN, NaN); // [1, 2, 3]
Array(3).fill(4); // [4, 4, 4]
[].fill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3}
If you need to do it many times, you can always write a function:
function makeArray(howMany, value){
var output = [];
while(howMany--){
output.push(value);
}
return output;
}
var data = makeArray(40, "Foo");
And, just for completeness (fiddling with the prototype of built-in objects is often not a good idea):
Array.prototype.fill = function(howMany, value){
while(howMany--){
this.push(value);
}
}
So you can now:
var data = [];
data.fill(40, "Foo");
Update: I've just seen your note about arraySize
being a constant or literal. If so, just replace all while(howMany--)
with good old for(var i=0; i<howMany; i++)
.