我正在寻找以下方法的任何替代方法,以创建包含1到N的JavaScript数组,其中N仅在运行时已知。

var foo = [];

for (var i = 1; i <= N; i++) {
   foo.push(i);
}

对我来说,我觉得应该有一种不用循环的方法。


当前回答

这可能是生成数字数组的最快方法

最短的

var a=[],b=N;while(b--)a[b]=b+1;

内联

var arr=(function(a,b){while(a--)b[a]=a;return b})(10,[]);
//arr=[0,1,2,3,4,5,6,7,8,9]

如果您想从1开始

var arr=(function(a,b){while(a--)b[a]=a+1;return b})(10,[]);
//arr=[1,2,3,4,5,6,7,8,9,10]

想要功能吗?

function range(a,b,c){c=[];while(a--)c[a]=a+b;return c}; //length,start,placeholder
var arr=range(10,5);
//arr=[5,6,7,8,9,10,11,12,13,14]

WHY?

while是最快的循环直接设置比推送更快[]比新阵列(10)更快它很短。。。查看第一个代码。然后看看这里的所有其他函数。

如果你喜欢,就不能没有

for(var a=[],b=7;b>0;a[--b]=b+1); //a=[1,2,3,4,5,6,7]

or

for(var a=[],b=7;b--;a[b]=b+1); //a=[1,2,3,4,5,6,7]

其他回答

使用ES6

const generateArray = n => [...Array(n)].map((_, index) => index + 1);

简单量程发生器:

    const min = 2000;
    const max = 2022;
    const range = Array.from({ length: max - min + 1 }, (v, k) => k + min); 
    console.log('range', range);

以下是摘要(在控制台中运行):

// setup:
var n = 10000000;
function* rangeIter(a, b) {
    for (let i = a; i <= b; ++i) yield i;
}
function range(n) { 
    let a = []
    for (; n--; a[n] = n);
    return a;
}
function sequence(max, step = 1) {
    return {
        [Symbol.iterator]: function* () {
            for (let i = 1; i <= max; i += step) yield i
        }
    }
}

var t0, t1, arr;
// tests
t0 = performance.now();
arr = Array.from({ length: n }, (a, i) => 1)
t1 = performance.now();
console.log("Array.from({ length: n }, (a, i) => 1) Took " + (t1 - t0) + " milliseconds.");

t0 = performance.now();
arr = range(n);
t1 = performance.now();
console.log("range(n) Took " + (t1 - t0) + " milliseconds.");

t0 = performance.now();
arr = Array.from(rangeIter(0, n));
t1 = performance.now();
console.log("Array.from(rangeIter(0, n)) Took " + (t1 - t0) + " milliseconds.");

t0 = performance.now();
arr = [...rangeIter(0, n)];
t1 = performance.now();
console.log("[...rangeIter(0, n)] Took " + (t1 - t0) + " milliseconds.");

t0 = performance.now();
arr = Array.from(sequence(n));
t1 = performance.now();
console.log("Array.from(sequence(n)) Took " + (t1 - t0) + " milliseconds.");

t0 = performance.now();
arr = [...sequence(n)];
t1 = performance.now();
console.log("[...sequence(n)] Took " + (t1 - t0) + " milliseconds.");

t0 = performance.now();
arr = Array(n).fill(0).map(Number.call, Number);
t1 = performance.now();
console.log("Array(n).fill(0).map(Number.call, Number) Took " + (t1 - t0) + " milliseconds.");

t0 = performance.now();
arr = Array.from(Array(n).keys());
t1 = performance.now();
console.log("Array.from(Array(n).keys()) Took " + (t1 - t0) + " milliseconds.");

t0 = performance.now();
arr = [...Array(n).keys()];
t1 = performance.now();
console.log("[...Array(n).keys()] Took " + (t1 - t0) + " milliseconds.");

最快的是Array(n).fill(0).map(Number.call,Number),第二个是[…Array(n).keys()]

但是。。。rangeIter的方式非常方便(可以内联),速度快,功能更强大

有一个小功能,它允许使用像[1,2]。范围(3,4)->[1,2,3,4]也适用于负参数。享受

Array.prototype.range = function(from, to)
{
   var range = (!to)? from : Math.abs(to - from) + 1, increase = from < to;
   var tmp = Array.apply(this, {"length": range}).map(function()
      {
         return (increase)?from++ : from--;
      }, Number);

   return this.concat(tmp);
};

Fast

这个解决方案可能是最快的——它是由lodash_.range函数启发而来的(但我的更简单、更快)

设N=10,i=0,a=阵列(N);而(i<N)a[i++]=i;控制台日志(a);

与当前(2020.12.11)相比,基于while/for的现有答案的性能优势

内存在开始时由a=数组(N)分配一次使用了增加索引i++——看起来比减少索引i快30%左右——(可能是因为CPU缓存在正向上更快)

在此答案中,使用了20多种其他解决方案进行了速度测试