Initializing an Array with a Single Value

后端 未结 10 1181
清酒与你
清酒与你 2020-12-12 23:34

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

for (var i = 0; i < arraySize; i++) array[i] = value;
10条回答
  •  失恋的感觉
    2020-12-13 00:15

    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.

提交回复
热议问题