在JavaScript中创建任意长度的零填充数组最有效的方法是什么?


当前回答

let arr = [...Array(100).fill(0)]

其他回答

匿名函数:

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

用for循环稍微短一点:

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

适用于任何对象,只需更改this.push()中的内容即可。

您甚至可以保存函数:

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

使用以下方法调用:

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

将元素添加到已存在的数组:

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

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

循环代码最短

a=i=[];for(;i<100;)a[i++]=0;

edit:
for(a=i=[];i<100;)a[i++]=0;
or
for(a=[],i=100;i--;)a[i]=0;

安全var版本

var a=[],i=0;for(;i<100;)a[i++]=0;

edit:
for(var i=100,a=[];i--;)a[i]=0;

在我的测试中,这是我电脑中最快的

1亿个元素需要大约350毫秒。

"0".repeat(100000000).split('');

对于相同数量的元素,map(()=>0)需要大约7000毫秒,这是一个巨大的差异

let filled=[];填充长度=10;fill.fill(0);console.log(已填充);

最快的方法是使用forEach=)

(我们保持IE<9的向后兼容性)

var fillArray = Array.prototype.forEach
    ? function(arr, n) {
         arr.forEach(function(_, index) { arr[index] = n; });
         return arr;
      }
    : function(arr, n) {
         var len = arr.length;
         arr.length = 0;
         while(len--) arr.push(n);
         return arr;
      };

// test
fillArray([1,2,3], 'X'); // => ['X', 'X', 'X']