連番配列の生成.js
#JavaScript
[0, 1, 2, 3, 4]
みたいなやつ。
0始まりの場合
Array.prototype.keys()
と
スプレッド構文
を使うと0からlength-1までの連番配列を得ることができます。
code:example.js
...new Array(5).keys()
// Expected Log Output : <Array>
0, 1, 2, 3, 4
Array.prototype.map()
のcallbackFnの第2引数でindexをもらえるので、それを使ってもいいでしょう。
code:example.js
...new Array(5)
.map((e, i) => i)
// Expected Log Output : <Array>
0, 1, 2, 3, 4
1始まりの場合
これは後者のほうが短くなります。前者だとmapを追加で書かなきゃいけないので
code:example.js
...new Array(5)
.map((e, i) => i + 1)
// Expected Log Output : <Array>
1, 2, 3, 4, 5
Author :
綾坂こと