1
0

javascriptで初期化した配列を作成する方法

Posted at

方法その1:変数に配列を格納する

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

方法その2:for文で作成する

const array = [];
for (let i = 0; i <= 9; i++) {
    array.push(i);
}

方法その3:Array.formを使う

const array = Array.from({ length: 10 }, (v, k) => k);

方法その4:Array()を使う

const array = [...Array(10)].map((v, i) => i);

Array(10)について補足
Array(10).map()と書きたくなるところだが、Array(10)で作成した配列は空配列ではなくemptyとなる。
※ここでの「空配列」とは[undefined, undefined,...] のような形のこと

emptyはnullでもundefinedでもない値のためmapが機能しない。

Array(10).map((v, i) => console.log(i));
結果
[ <10 empty items> ]
1
0
0

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