如何创建一个包含1 ... N的数组 [英] How to create an array containing 1...N

查看:82
本文介绍了如何创建一个包含1 ... N的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找以下替代方法,以创建一个包含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的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆