tags:

views:

55

answers:

3

Is there a more compact way to do this sort of initialization?

for (var i = 0; i < arraySize; i++) array[i] = value;
+2  A: 
while(arraySize--) array.push(value);

no initialization (that i know of)

DoXicK
In many cases, “arraySize” wouldn’t be mutable (could be a constant or literal or — I know, bad practice — “array.length”). By representing the size as a variable, I made this bit unclear.
byoogle
true: "for(var i = arraySize; i--;) array.push(value);" then :-) but i think you figured that out already
DoXicK
You’re right — that syntax does shave five characters off. ;-)
byoogle
A: 

Not Javascript-specific, but in a few languages you can go for (item in array) item=value;

Henrik Erlandsson
In Javascript, `for-in` is highly discouraged to be used in arrays or array-like objects. Also, it wouldn't work to initialize an empty array, I think that's what the OP wants to do...
CMS
A: 

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++).

Álvaro G. Vicario