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

var foo = [];

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

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


当前回答

如果我得到了你想要的,你需要一个数字数组1..n,以后可以循环使用。

如果这就是你所需要的,你能代替它吗?

var foo = new Array(45); // create an empty array with length 45

然后当你想使用它时…(例如,未优化)

for(var i = 0; i < foo.length; i++){
  document.write('Item: ' + (i + 1) + ' of ' + foo.length + '<br/>'); 
}

例如,如果你不需要在数组中存储任何东西,你只需要一个长度合适的容器,你可以遍历它。。。这可能更容易。

请在此处查看实际操作:http://jsfiddle.net/3kcvm/

其他回答

我能产生的最少代码:

for(foo=[x=100]; x; foo[x-1]=x--);
console.log(foo);

数组(…数组(9)).map((_,i)=>i);console.log(数组(…数组(9)).map((_,i)=>i))

ES5版本,效率很低,但可能是最短的一个,它是一个表达式,而不是一个变量填充有例如for循环的语句:

(Array(N)+'').split(',').map(function(d,i){return i})

使用ES6,您可以做到:

// `n` is the size you want to initialize your array
// `null` is what the array will be filled with (can be any other value)
Array(n).fill(null)

填充Array的新方法是:

const array=[…array(5).keys()]console.log(数组)

结果将为:[0,1,2,3,4]