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

var foo = [];

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

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


当前回答

试试这个

[…Array.from({length:30}).keys()]

其他回答

最终总结报告。。Drrruummm Rolll公司-

这是在不使用ES6的情况下生成大小为N(此处为10)的数组的最短代码。Cocco上面的版本很接近,但不是最短的。

(function(n){for(a=[];n--;a[n]=n+1);return a})(10)

但这场“代码高尔夫”(用最少的源代码字节来解决特定问题的比赛)无可争议的赢家是Niko Ruotsalainen。使用数组构造函数和ES6扩展运算符。(大多数ES6语法都是有效的typeScript,但下面不是。所以在使用它时要谨慎)

[...Array(10).keys()]

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

// 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的方式非常方便(可以内联),速度快,功能更强大

试试看:

var foo = [1, 2, 3, 4, 5];

如果您正在使用CoffeeScript,可以通过执行以下操作创建范围:

var foo = [1..5]; 

否则,如果您使用的是普通JavaScript,那么如果要将数组初始化为可变长度,则必须使用循环。

对以上内容进行改进:

var range = function (n) {
  return Array(n).join().split(',').map(function(e, i) { return i; });
}  

可以获得以下选项:

1) Array.init设置为值v

var arrayInitTo = function (n,v) {
  return Array(n).join().split(',').map(function() { return v; });
}; 

2) 获得反向范围:

var rangeRev = function (n) {
  return Array(n).join().split(',').map(function() { return n--; });
};

比字符串变体简单一点:

// create range by N
Array(N).join(0).split(0);

// create a range starting with 0 as the value
Array(7).join(0).split(0).map((v, i) => i + 1) // [1, 2, 3, 4, 5, 6, 7]

更新(2018年1月4日):更新以解决确切的OP问题。感谢@lessless发出此消息!