在JavaScript中创建任意长度的零填充数组最有效的方法是什么?
当前回答
在答案中没有看到这种方法,所以这里是:
"0".repeat( 200 ).split("").map( parseFloat )
结果,您将得到长度为200的零值数组:
[ 0, 0, 0, 0, ... 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对此有何看法?:-)
创建全新阵列
new Array(arrayLength).fill(0);
在现有阵列的末尾添加一些值
[…existingArray,…new Array(numberOfElementsToAdd).fill(0)]
实例
//**创建全新阵列**console.log(新数组(5).fill(0));//**在现有阵列的末尾添加一些值**让existingArray=[1,2,3]console.log([…existingArray,…new Array(5).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
在我的测试中,这是我电脑中最快的
1亿个元素需要大约350毫秒。
"0".repeat(100000000).split('');
对于相同数量的元素,map(()=>0)需要大约7000毫秒,这是一个巨大的差异
新的Array(51).join(“0”).split(“”)怎么样?