在 JavaScript 中从 1..20 创建整数数组的最简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6299500/
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
Tersest way to create an array of integers from 1..20 in JavaScript
提问by artlung
What would be the tersest way to create this array:
创建此数组的最简洁方法是什么:
var x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
For example, a for
loop:
例如,一个for
循环:
var x = [];
for (var i=1;i<=20;i++) {
x.push(i);
}
Or a while
loop:
或者while
循环:
var x = [], i = 1, endInt = 20;
while (i <= endInt) {
x.push(i);
i++;
}
Would there be other examples that would be terser -- in other words -- less code? I'm thinking of things like in Ruby where the equivalent code I believe would be as simple as 1..20
. I'm not aware of syntax like that in JavaScript but I'm wondering if there are shorter ways to do that same thing.
是否还有其他更简洁的示例——换句话说——更少的代码?我正在考虑诸如在 Ruby 中的事情,其中我认为等效的代码会像1..20
. 我不知道 JavaScript 中的语法,但我想知道是否有更短的方法来做同样的事情。
UPDATE:I wasn't thinking of removing semicolons or var
for answers in the question, but I have to admit the question implies that. I am more curious about algorithms than shaving bytes. Sorry if I was unclear! Also, making it into a function is simple enough, just slap function range(start, end) { /* guts here */ }
around it and you're there. The question is are there novel approaches to the "guts."
更新:我没有考虑删除分号或var
问题中的答案,但我不得不承认这个问题暗示了这一点。我对算法比对字节更感兴趣。对不起,如果我不清楚!此外,将它变成一个函数也很简单,只需轻轻拍function range(start, end) { /* guts here */ }
一下它就可以了。问题是是否有针对“胆量”的新方法。
回答by ninjagecko
After thinking about it a bit, this is the shortest implementation of the standard range(N)
function in JavaScript I could come up with:
稍微思考了一下,这是range(N)
我能想到的 JavaScript标准函数的最短实现:
function range1(i){return i?range1(i-1).concat(i):[]}
Note: Do not use this in production; it's O(N^2)
注意:不要在生产中使用它;它是 O(N^2)
Contrast with current top-voted answer:
与当前最高投票的答案对比:
function range1(i){var x=[];var i=1;while(x.push(i++)<i){};return x}
Example:
例子:
> range1(5)
[1, 2, 3, 4, 5]
This is like the poster child for recursion, though I was expecting it to be longer until I thought of ternary-if-statement, which brings it down to 42 necessary characters.
这就像递归的典型代表,尽管我原以为它会更长,直到我想到了三元 if 语句,这将其减少到 42 个必要的字符。
Note that the "standard" range
function returning [start,end) can be written by doing .concat(i-1)
.
请注意,range
返回 [start,end)的“标准”函数可以通过执行.concat(i-1)
.
Update: Ooh, I discovered an incredibly short version with ugly imperative syntax by abusing for loops, reverse-ordering, the fact that assignments return a value: for(y=[],i=20;y[--i]=i;){}
consisting of only 25 characters (though you will want var y
which you can insert into a for loop, and +1 if you don't want 0...19). While it is not shorter if you need to define a function, it is shorter than i?r(i-1).concat(i):[]
if you do not need to make a function.
更新:哦,我通过滥用 for 循环、反向排序、赋值返回一个值的事实发现了一个令人难以置信的短版本,它具有丑陋的命令式语法:for(y=[],i=20;y[--i]=i;){}
仅包含 25 个字符(尽管您会想要var y
它可以插入到 for 循环中,如果您不想要 0...19,则 +1)。虽然如果您需要定义一个函数,它并不短,但它比i?r(i-1).concat(i):[]
您不需要创建一个函数时更短。
Favorite method
喜欢的方法
Update Sep13,2015:
2015 年 9 月 13 日更新:
Just came up with this new method which works with browsers which support the ES6 standard:
刚刚提出了这种适用于支持 ES6 标准的浏览器的新方法:
> Array(5).fill().map((x,i)=>i)
[0, 1, 2, 3, 4]
Also this:
还有这个:
> Array.from(Array(5),(x,i)=>i)
[0, 1, 2, 3, 4]
Added some performance profiling testcases: it seems that everything besides a standard in-order for-loop is 10x slower, at least on V8. https://jsperf.com/array-range-in-javascript(Of course, none of this matters if you're programming in a functional style anyway and would hit every element with a function call anyway.)
添加了一些性能分析测试用例:似乎除了标准的有序 for 循环之外的一切都慢了 10 倍,至少在 V8 上。https://jsperf.com/array-range-in-javascript(当然,如果您以函数式风格进行编程并且无论如何都会通过函数调用命中每个元素,那么这些都不重要。)
回答by Kristjan Liiva
It can be done with features from the ES6, currently only supported by Firefox thou. I found a compatibility table here: http://kangax.github.io/compat-table/es6/
它可以通过 ES6 的特性来完成,目前只有 Firefox 支持。我在这里找到了一个兼容性表:http: //kangax.github.io/compat-table/es6/
Array.from(new Array(20), (x,i) => i+1)
If you want to have some other range then I guess you could do
如果你想有一些其他的范围,那么我想你可以做
Array.from(new Array(5), (x,i) => i+5)
Which would then be [5,6,7,8,9]
那么这将是 [5,6,7,8,9]
回答by EndangeredMassa
You can do this with a while loop where the push happens inside the condition.Array.push returns the length of the array, which happens to be the same as the value in this case. So, you can do the following:
您可以使用 while 循环执行此操作,其中推送发生在条件内部。Array.push 返回数组的长度,恰好与本例中的值相同。因此,您可以执行以下操作:
x = []; //normally would use var here
i = 1; //normally would use var here
while(x.push(i++)<20){}
//at this point, x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Condensed version (31 characters)
精简版(31 个字符)
x=[];i=1;while(x.push(i++)<20);
回答by cocco
while-- is the way to go
而--是要走的路
var a=[],b=10;while(b--)a[b]=b+1
returns [1,2,3,4,5,6,7,8,9,10]
返回 [1,2,3,4,5,6,7,8,9,10]
explained with start & length
用开始和长度解释
var array=[],length=20,start=5;while(length--)array[length]=length+start
returns [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
返回 [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
want range?
想要范围?
explained with start & end
用开始和结束解释
var array=[],end=30,start=25,a=end-start+1;while(a--)array[a]=end--
returns [25, 26, 27, 28, 29, 30]
返回 [25, 26, 27, 28, 29, 30]
for --
为了 -
for(var a=[],b=20;b>0;b--,a[b]=b+1)
for++
对于++
for(var a=[],b=0;b<20;b++,a[b]=b+1)
WHY is this theway to go?
为什么要走这条路?
while -- is prolly the fastest loop;
direct setting is faster than push & concat;
[] is also faster than new Array(10);
it's not much longer code than all the others
while -- 是最快的循环;
直接设置比 push & concat 更快;
[] 也比 new Array(10) 快;
它的代码并不比所有其他代码长
byte saving techniques:
字节保存技术:
- use the arguments as a placholder forthe in function variables
- don't use new Array(),push(),concat() if not needed
- place "(){};," only when needed.
- use a,b,c,d... in short functions.
- 使用参数作为函数变量的占位符
- 如果不需要,不要使用 new Array(),push(),concat()
- 仅在需要时放置 "(){};,"。
- 在短函数中使用 a,b,c,d...。
so if u want a function for this
所以如果你想要一个功能
with start,end (range)
开始,结束(范围)
function range(a,b,c,d){d=[];c=b-a+1;while(c--)d[c]=b--;return d}
so now range(3,7) returns [3,4,5,6,7]
所以现在 range(3,7) 返回 [3,4,5,6,7]
u save bytes in many ways here and this function is also very fast as it does not use concat, push, new Array and it's made with a while --
你在这里以多种方式保存字节,这个函数也非常快,因为它不使用 concat、push、new Array 并且它是用一段时间制作的——
回答by caroso1222
Using ES6
使用 ES6
numArr = Array(5).fill(0).reduce(arr=>{ arr.push(arr.length); return arr },[])
numArr = Array(5).fill(0).reduce(arr=>{ arr.push(arr.length); return arr },[])
回答by MillsJROSS
You could always create a function...
你总是可以创建一个函数......
function createNumArray(a, b) {
var arr = [],
i = a;
while((arr[arr.length] = i) < b) {i++}
return arr;
}
Which allows you to write succinct code later on such as...
这允许您稍后编写简洁的代码,例如...
var arr = createNumArray(1, 20);
回答by KooiInc
I suppose this is the shortest way:
我想这是最短的方法:
var i=0, arr = [];
while (i++<20){
arr.push(i);
}
or associating on the 'perverse' code in EndangeredMassa's answer:
或关联EndangeredMassa回答中的“反常”代码:
var i,arr; while (i=i||1, (arr=arr||[]).push(i++)<20){}
回答by Robert
I can't think of a way with less characters than ~46:
我想不出字符少于 ~46 的方法:
var a=[];while(a.length<20)a.push(a.length+1);
var a=[];while(a.length<20)a.push(a.length+1);
Granted, you could make a function out of that.
当然,您可以从中创建一个函数。
Reading your comments about a function, you could do something like
阅读您对函数的评论,您可以执行以下操作
var range = function (start, end) {
var arr = [];
while (start <= end) {
arr.push(start++)
}
return arr;
};
Then range(1, 20)
would return the array as expected.
然后range(1, 20)
将按预期返回数组。
回答by rob
If you are looking to shave characters off anyway possible without regard for readability, this is the best I can do:
如果您希望在不考虑可读性的情况下以任何方式剃掉字符,这是我能做的最好的事情:
var x=[],i=0
while(i<20)
x[i]=i+++1
Not a lot better than yours though.
不过比你的好不了多少。
Edit:
编辑:
Actually this works better and shaves off a couple characters:
实际上,这效果更好,并减少了几个字符:
var x=[],i=0
while(i<20)
x[i]=++i
Edit 2:
编辑2:
And here's my entry for a general "range" function in the least number of characters:
这是我输入的最少字符数的一般“范围”函数:
function range(s,e){var x=[];while(s<e+1)x.push(s++);return x}
Again, don't write code this way. :)
同样,不要以这种方式编写代码。:)
回答by Hasan Fahim
In my knowledge, the option of using for loop, as you mentioned, is the most tersest.
据我所知,正如您所提到的,使用 for 循环的选项是最简洁的。
That is,
那是,
var x = [];
for (var i=1;i<=20;i++) {
x.push(i);
}