LoginSignup
2
2

n回ループする処理をJS/TSで書く

Last updated at Posted at 2021-08-02
const count = 5
Array.from({ length: count }).map((_, index) => console.log(index))

0
1
2
3
4

以下の書き方は、推奨ではなく、「こんな書き方も出来るよ」という内容です。
不必要にメモリを消費するので、使うとしてもテストコード内にとどめるのが良いと思います。
書き方のメリットは以下です。

  • 簡潔に書ける。
  • 高階関数が使える。

[...Array(n)]
// or
Array(3).fill()

n に要素数を入れます。


これ(↓)で、要素数が 3 で中身が空(undefined)の配列が出来ます。

> [...Array(3)]
[ undefined, undefined, undefined ]

> [...Array(3)].length
3
> Array(3).fill()
[ undefined, undefined, undefined ]

> Array(3).fill().length
3

map で使う。

> [...Array(3)].map((val, index) => index)
[ 0, 1, 2 ]

forEach で使う。

> [...Array(3)].forEach((val, index) => console.log(index))
0
1
2
2
2
3

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
2