在JavaScript中创建任意长度的零填充数组最有效的方法是什么?
当前回答
let arr = [...Array(100).fill(0)]
其他回答
循环代码最短
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;
我最快的功能是:
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
使用本机push和shift向数组中添加项比声明数组范围并引用每个项来设置其值快得多(大约10倍)。
fyi:在firebug(firefox扩展)中运行时,第一个循环一直在倒计时,我总是会得到更快的时间。
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
我很想知道T.J.Crowder对此有何看法?:-)
我知道这不是问题的目的,但这里有一个开箱即用的想法。为什么?我的CSci教授指出,用零来“净化”数据并没有什么神奇之处。因此,最有效的方法是根本不做!只有当数据需要为零作为初始条件(如某些求和)时才这样做——这通常不是大多数应用程序的情况。
在我的测试中,这是我电脑中最快的
1亿个元素需要大约350毫秒。
"0".repeat(100000000).split('');
对于相同数量的元素,map(()=>0)需要大约7000毫秒,这是一个巨大的差异
匿名函数:
(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