Most efficient way to create a zero filled JavaScript array?

前端 未结 30 1226
花落未央
花落未央 2020-11-22 05:58

What is the most efficient way to create an arbitrary length zero filled array in JavaScript?

相关标签:
30条回答
  • 2020-11-22 06:06

    By default Uint8Array, Uint16Array and Uint32Array classes keep zeros as its values, so you don't need any complex filling techniques, just do:

    var ary = new Uint8Array(10);
    

    all elements of array ary will be zeros by default.

    0 讨论(0)
  • 2020-11-22 06:06

    It might be worth pointing out, that Array.prototype.fill had been added as part of the ECMAScript 6 (Harmony) proposal. I would rather go with the polyfill written below, before considering other options mentioned on the thread.

    if (!Array.prototype.fill) {
      Array.prototype.fill = function(value) {
    
        // Steps 1-2.
        if (this == null) {
          throw new TypeError('this is null or not defined');
        }
    
        var O = Object(this);
    
        // Steps 3-5.
        var len = O.length >>> 0;
    
        // Steps 6-7.
        var start = arguments[1];
        var relativeStart = start >> 0;
    
        // Step 8.
        var k = relativeStart < 0 ?
          Math.max(len + relativeStart, 0) :
          Math.min(relativeStart, len);
    
        // Steps 9-10.
        var end = arguments[2];
        var relativeEnd = end === undefined ?
          len : end >> 0;
    
        // Step 11.
        var final = relativeEnd < 0 ?
          Math.max(len + relativeEnd, 0) :
          Math.min(relativeEnd, len);
    
        // Step 12.
        while (k < final) {
          O[k] = value;
          k++;
        }
    
        // Step 13.
        return O;
      };
    }
    
    0 讨论(0)
  • 2020-11-22 06:07
    function zeroFilledArray(size) {
        return new Array(size + 1).join('0').split('');
    }
    
    0 讨论(0)
  • 2020-11-22 06:07

    I have nothing against:

    Array.apply(null, Array(5)).map(Number.prototype.valueOf,0);
    new Array(5+1).join('0').split('').map(parseFloat);
    

    suggested by Zertosh, but in a new ES6 array extensions allow you to do this natively with fill method. Now IE edge, Chrome and FF supports it, but check the compatibility table

    new Array(3).fill(0) will give you [0, 0, 0]. You can fill the array with any value like new Array(5).fill('abc') (even objects and other arrays).

    On top of that you can modify previous arrays with fill:

    arr = [1, 2, 3, 4, 5, 6]
    arr.fill(9, 3, 5)  # what to fill, start, end
    

    which gives you: [1, 2, 3, 9, 9, 6]

    0 讨论(0)
  • 2020-11-22 06:10

    ES6 introduces Array.prototype.fill. It can be used like this:

    new Array(len).fill(0);
    

    Not sure if it's fast, but I like it because it's short and self-describing.

    It's still not in IE (check compatibility), but there's a polyfill available.

    0 讨论(0)
  • 2020-11-22 06:10

    My fastest function would be:

    function newFilledArray(len, val) {
        var a = [];
        while(len--){
            a.push(val);
        }
        return a;
    }
    
    var st = (new Date()).getTime();
    newFilledArray(1000000, 0)
    console.log((new Date()).getTime() - st); // returned 63, 65, 62 milliseconds
    

    Using the native push and shift to add items to the array is much faster (about 10 times) than declaring the array scope and referencing each item to set it's value.

    fyi: I consistently get faster times with the first loop, which is counting down, when running this in firebug (firefox extension).

    var a = [];
    var len = 1000000;
    var st = (new Date()).getTime();
    while(len){
        a.push(0);
        len -= 1;
    }
    console.log((new Date()).getTime() - st); // returned 863, 894, 875 milliseconds
    st = (new Date()).getTime();
    len = 1000000;
    a = [];
    for(var i = 0; i < len; i++){
        a.push(0);
    }
    console.log((new Date()).getTime() - st); // returned 1155, 1179, 1163 milliseconds
    

    I'm interested to know what T.J. Crowder makes of that ? :-)

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