Initializing an Array with a Single Value

后端 未结 10 1179
清酒与你
清酒与你 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-12 23:58

    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);
    
    0 讨论(0)
  • 2020-12-13 00:03

    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);})
    
    0 讨论(0)
  • 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)

    • Chrome 45 (36 1)
    • Firefox (Gecko) 31 (31)
    • Internet Explorer Not supported
    • Opera Not supported
    • Safari 7.1

    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}
    
    0 讨论(0)
  • 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<howMany; i++).

    0 讨论(0)
提交回复
热议问题