创建一个包含1 ... N JavaScript数组 [英] Create a JavaScript array containing 1...N

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

问题描述

我在寻找任何替代的下面通过对n,其中n只在运行时已知的创建包含JavaScript数组1。

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..1 你可后来通过。循环

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 JavaScript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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