Most efficient way to create a zero filled JavaScript array?

前端 未结 30 1642
花落未央
花落未央 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:22

    using object notation

    var x = [];
    

    zero filled? like...

    var x = [0,0,0,0,0,0];
    

    filled with 'undefined'...

    var x = new Array(7);
    

    obj notation with zeros

    var x = [];
    for (var i = 0; i < 10; i++) x[i] = 0;
    

    As a side note, if you modify Array's prototype, both

    var x = new Array();
    

    and

    var y = [];
    

    will have those prototype modifications

    At any rate, I wouldn't be overly concerned with the efficiency or speed of this operation, there are plenty of other things that you will likely be doing that are far more wasteful and expensive than instanciating an array of arbitrary length containing zeros.

提交回复
热议问题