在JavaScript中创建任意长度的零填充数组最有效的方法是什么?
当前回答
这里还有一个不错的选择http://www.2ality.com/2013/11/initializing-arrays.html
function fillArrayWithNumbers(n) {
var arr = Array.apply(null, Array(n));
return arr.map(function (x, i) { return i });
}
其他回答
ES6引入了Array.prototype.fill。它可以这样使用:
new Array(len).fill(0);
不确定它是否很快,但我喜欢它,因为它很短,很自我描述。
它仍然不在IE中(检查兼容性),但有一个polyfill可用。
这里最快的是
(arr = []).length = len; arr.fill(0);
递归解决方案
正如其他人所指出的,利用.contat()通常提供快速解决方案。下面是一个简单的递归解决方案:
函数zeroFill(len,a){return len<=(a||(a=[0])).长度?a.切片(0,len):zeroFill(长度,a.concat(a))}console.log(zeroFill(5));
以及一个通用递归数组填充函数:
函数填充(len,v){返回长度<=(v=[].contat(v,v)).length?v.slice(0,len):填充(len,v)}console.log(fill(5,'abc'));
匿名函数:
(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
已经提到的ES6填充方法很好地解决了这个问题。截至目前,大多数现代桌面浏览器已经支持所需的Array原型方法(Chromium、FF、Edge和Safari)[1]。您可以在MDN上查找详细信息。一个简单的用法示例是
a = new Array(10).fill(0);
考虑到当前的浏览器支持,除非您确定您的受众使用的是现代桌面浏览器,否则您应该谨慎使用。