2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

全部ES6のループ文にしたかった時の最後の難関だったfor (let i = 0; i < 10; i++)をやっと抹殺した

Last updated at Posted at 2020-03-05

目的

要素が10個のArrayをつくる

追記・結論

これが一番簡潔です。

const array = Array(10).fill(0).map((_, idx) => ({
    id: idx,
    name: "hoge"
}));

スクリーンショット 2020-11-13 9.25.38.png

2022/3/1 さらに追記

これが一番シンプルです。

[...Array(10)].map((_, idx) => ({

憎きfor文

const array = [];
for (let i = 0; i < 10; i++) {
  const obj = {
    id: i,
    name: "hoge"
  };
  array.push(obj);
}

[...Array(10)]

const array = [...Array(10)].map((_, idx) => 
  return {
    id: idx,
    name: "hoge"
  };
);

これだとエラー
(lengthは10だけどemptyの配列が作られた)

Array.from(Array(10))

const array = Array.from(Array(10)).map((_, idx) => 
  return {
    id: idx,
    name: "hoge"
  };
);

これで動いた

参考:
https://stackoverflow.com/questions/10993824/do-something-n-times-declarative-syntax
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/from

関連記事

現場でよく使うJS ES6ループ文まとめ

2
3
5

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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?