Initializing an Array with a Single Value

后端 未结 10 1178
清酒与你
清酒与你 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:49

    For efficiency, I would avoid push. So simply

    for (var i = 0; i < arraySize; i++) array[i] = value; 
    

    For IE10:

    array = new Array(arraySize); 
    for (var i = 0; i < arraySize; i++) array[i] = value; 
    

    Edit: modified as discussed in the comments.

    0 讨论(0)
  • 2020-12-12 23:51

    One short way of doing it would be:

    var arr = Array(arraySize).fill(value);
    

    Would make arr = Array [ 0, 0, 0, 0, 0 ] if arraySize == 5 and value == 0, for example.

    0 讨论(0)
  • 2020-12-12 23:51

    This is an old question, but I use this in modern JS:

    [...new Array(1000000)].map(()=>42);
    
    0 讨论(0)
  • 2020-12-12 23:54

    This is not as compact but is arguably more direct.

    array = Array.apply(null, new Array(arraySize)).map(function () {return value;});
    
    0 讨论(0)
  • 2020-12-12 23:56
    while(arraySize--) array.push(value);
    

    no initialization (that i know of)


    Update

    Since ever posting this answer 4 years ago, people seem to keep coming back here for this answer. For benchmarking purposes I made a JSPerf with some different solutions.

    The solution above here isn't the quickest, although it's short. To stick to the same short style, but with a better performance:

    while(size--) array[size] = value;
    

    Update Feb 2016 Updated the JSPerf with a new revision with more testcases.

    If performance doesn't matter and you want a one-liner:

    var value = 1234, // can be replaced by a fixed value
        size  = 1000, // can be replaced by a fixed value
        array = Array.apply(null,{length: size}).map(function() { return value; });
    

    A more performant solution (in one, dirty, line): Be aware: this replaces existsing value, size and i variables in the scope

    for(var i = 0, value = 1234, size = 1000, array = new Array(1000); i < size; i++) array[i] = value;
    
    0 讨论(0)
  • 2020-12-12 23:58

    I think this is nice, short and elegant:

    // assuming `value` is what you want to fill the array with
    // and `arraySize` is the size of the array
    Array(arraySize).fill(value);
    
    0 讨论(0)
提交回复
热议问题