javascript 数字 1-20 的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19337275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Array with numbers 1-20
提问by Phil Powis
I'm brand new to javascript. I was working through a problem earlier where I needed an array that included the numbers 1 thru 20.
我是 javascript 的新手。我之前正在解决一个问题,我需要一个包含数字 1 到 20 的数组。
I did this with the following:
我用以下方法做到了这一点:
var numberArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
QUESTION:
问题:
I can't help but think that this is not efficient (and certainly not scalable). Is there a way to create an array that automatically populates with sequential values between 1 and 20, or 1 and 1000 for instance?
我不禁认为这效率不高(当然也不能扩展)。有没有办法创建一个数组,例如自动填充 1 到 20 或 1 到 1000 之间的顺序值?
回答by KooiInc
Here's a oneliner:
这是一个单线:
var myArr = Array(20).join().split(',').map(function(a){return this.i++},{i:1});
or a tiny bit shorter:
或者稍微短一点:
var myArr = (''+Array(20)).split(',').map(function(){return this[0]++;}, [1]);
Both methods create an empty Arraywith 20 empty elements (i.e. elements with value undefined). On a thus created Arraythe mapmethod can't be applied 1, so the join(or string addition) and splittrick transforms it to an Arraythat knows it. Now the mapcallback (see the MDN link) does nothing more than sending an increment of the initial value ({i:1}or [1]) back for each element of the Array, and after that, myArrcontains 20 numeric values from 1 to 20.
这两种方法都创建了一个Array包含 20 个空元素(即具有 value 的元素undefined)的空。在这样创建Array的map方法上不能应用1,因此join(或字符串添加)和split技巧将其转换为Array知道它的方法。现在map回调(参见 MDN 链接)只是为 的每个元素发送初始值({i:1}或[1])的增量Array,然后myArr包含 20 个从 1 到 20 的数值。
Addendum: ES20xx
附录:ES20xx
[...Array(21).keys()].slice(1);
Array.map=> See also...
Array.map=>另见...
1Why not? See this SO answer, and this onefor a more profound explanation
回答by Nick
You could use a simple loop to do what you want;
你可以使用一个简单的循环来做你想做的事;
var numberArray = [];
for(var i = 1; i <= 20; i++){
numberArray.push(i);
}
console.log(numberArray);

