Is there a more compact way to do this sort of initialization?
for (var i = 0; i < arraySize; i++) array[i] = value;
Is there a more compact way to do this sort of initialization?
for (var i = 0; i < arraySize; i++) array[i] = value;
while(arraySize--) array.push(value);
no initialization (that i know of)
Not Javascript-specific, but in a few languages you can go for (item in array) item=value;
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++)
.