LoginSignup
2
1

More than 3 years have passed since last update.

TypeScriptで連番の配列を1行で作成する

Posted at

tl;dr

[...Array(n)].map((_:undefind, idx:number) => idx))で連番の配列を作成できます。

説明

[...Array(number)]を実行すると、number個のundefinedの一次元配列を返します。

const foo = [...Array(5)]
console.log(foo)

実行結果:

[ undefined, undefined, undefined, undefined, undefined ]

そこで、map関数のindexを使って値を作成します。

const foo = [...Array(5)].map((_:undefined, idx:number) => idx)
console.log(foo)

実行結果:

[ 0, 1, 2, 3, 4 ]

以上。

2
1
2

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
2
1