使用一行程式碼建立一個 `[0, 1, ..., N - 1]` 的陣列
這裡有兩種 compact 程式碼序列方式,來產生一個 [0, 1, ..., N-1]
的 N
個元素的陣列:
方法一(ES5)
Array.apply(null, {length: N}).map(Function.call, Number);
簡要說明
Array.apply(null, {length: N)
回傳一個N
個元素的陣列,裡面陣列元素都是為undefined
(i.e.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]
。
更深入的解釋,請前往這裡。
方法二(ES6)
Array.from(new Array(N), (val, index) => index);
簡要說明
A = new Array(N)
回傳一個有N
個 holes 的陣列(i.e.A = [,,,...]
,但是x
在0...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]
。
還有一件事情
如果你真的想要排序 [1, 2, …, N],方法一改為:
Array.apply(null, {length: N}).map(function(value, index){
return index + 1;
});
和 方法二:
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