仅用一行生成`[0, 1, ..., N-1]`数列
使用下面一行代码,我们就可以生成0…(N-1)数列。
方法1 (需要 ES5)
Array.apply(null, {length: N}).map(Function.call, Number);
简要说明
Array.apply(null, {length: N})
返回一个由undefined
填充的长度为N
的数组(例如A = [undefined, undefined, ...]
)。A.map(Function.call, Number)
返回一个长度为N
的数组,它的索引为I
的元素为Function.call.call(Number, undefined, I, A)
的结果。Function.call.call(Number, undefined, I, A)
可转化为Number(I)
,正好就是I
。- 结果为:
[0, 1, ..., N-1]
。
更全面的介绍,请看这里.
方法2 (需要 ES6)
这里用到了Array.from
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/from
Array.from(new Array(N),(val,index)=>index);
简要说明
A = new Array(N)
返回一个有N
个_小孔_的数组 (例如A = [,,,...]
, 但是对于x
in0...N-1
时A[x] = undefined
)。F = (val,index)=>index
即function F (val, index) { return index; }
。Array.from(A, F)
返回一个长度为N
的数组,它的索引为I
的元素为F(A[I], I)
的结果,也就是I
。- 结果为:
[0, 1, ..., N-1]
。
One More Thing
如果你需要[1, 2, …, N]序列, 方法1 可改为:
Array.apply(null, {length: N}).map(function(value, index){
return index + 1;
});
方法2可改为:
Array.from(new Array(N),(val,index)=>index+1);
MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW
MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW