问题描述
我正在寻找以下任何替代方案,以创建包含 1 到 N 的 JavaScript 数组,其中 N 仅在运行时已知.
I'm looking for any alternatives to the below for creating a JavaScript array containing 1 through to N where N is only known at runtime.
var foo = [];
for (var i = 1; i <= N; i++) {
foo.push(i);
}
对我来说,应该有一种没有循环的方法.
To me it feels like there should be a way of doing this without the loop.
推荐答案
如果我明白了您的要求,您需要一个数字数组 1..n
,您可以稍后循环遍历.
If I get what you are after, you want an array of numbers 1..n
that you can later loop through.
如果这就是你所需要的,你可以这样做吗?
If this is all you need, can you do this instead?
var foo = new Array(45); // create an empty array with length 45
然后当你想使用它时......(未优化,仅举个例子)
then when you want to use it... (un-optimized, just for example)
for(var i = 0; i < foo.length; i++){
document.write('Item: ' + (i + 1) + ' of ' + foo.length + '<br/>');
}
例如如果您不需要在数组中存储任何内容,您只需要一个可以迭代的长度合适的容器......这可能更容易.
e.g. if you don't need to store anything in the array, you just need a container of the right length that you can iterate over... this might be easier.
在这里查看它的实际效果:http://jsfiddle.net/3kcvm/
See it in action here: http://jsfiddle.net/3kcvm/
这篇关于如何创建一个包含 1...N 的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!