Most efficient way to create a zero filled JavaScript array?

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

    Anonymous function:

    (function(n) { while(n-- && this.push(0)); return this; }).call([], 5);
    // => [0, 0, 0, 0, 0]
    

    A bit shorter with for-loop:

    (function(n) { for(;n--;this.push(0)); return this; }).call([], 5);
    // => [0, 0, 0, 0, 0]
    

    Works with any Object, just change what's inside this.push().

    You can even save the function:

    function fill(size, content) {
      for(;size--;this.push(content));
      return this;
    }
    

    Call it using:

    var helloArray = fill.call([], 5, 'hello');
    // => ['hello', 'hello', 'hello', 'hello', 'hello']
    

    Adding elements to an already existing array:

    var helloWorldArray = fill.call(helloArray, 5, 'world');
    // => ['hello', 'hello', 'hello', 'hello', 'hello', 'world', 'world', 'world', 'world', 'world']
    

    Performance: http://jsperf.com/zero-filled-array-creation/25

提交回复
热议问题