LoginSignup
226
135

More than 1 year has passed since last update.

JavaScriptで[ 0, 1, 2, 3, 4 ]のような連番の配列を生成する方法

Last updated at Posted at 2019-07-19

JavaScriptで[ 0, 1, 2, 3, 4 ]のような連番の配列を生成する方法です。

[...Array(5)].map((_, i) => i) //=> [ 0, 1, 2, 3, 4 ]

spread operator...と、arrow function=>を使っているためES6以降で動作します。

解説

上のコードは3つのパートに分けられます。

パート1: Array(5)

これは要素数が5つ(=スロットが5つあるだけ)の空っぽの配列を作る。undefinedが5つ入るわけでない。

Array(5) //=> [ <5 empty items> ]

パート2: [...Array(5)][... ]の部分

要素数が5つある配列をspread operatorにかけて、undefined5つの配列に変形している。

[...Array(5)] //=> [ undefined, undefined, undefined, undefined, undefined ]

パート3: .map((_, i) => i)

mapメソッドでundefined5つの配列を、インデックス番号が値になった配列に変形している。

[ undefined, undefined, undefined, undefined, undefined ].map((_, i) => i)

応用: [ 1, 2, 3, 4, 5 ]のように1始まりにしたい場合

[...Array(5)].map((_, i) => i + 1) //=> [ 1, 2, 3, 4, 5 ]
//                            ^^^ mapのコールバック関数で+1の演算をすればよい  

(_, i) =>のアンダースコアは第1引数を使わないという意味です。第2引数だけ使いたいのですが、第1引数も受け取る必要があるため、_を置いています。

226
135
8

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
226
135