LoginSignup
2
2

More than 3 years have passed since last update.

[JavaScript]配列をループで処理する4つの方法と注意点(for, forEach, for...of, for...in)

Last updated at Posted at 2019-08-04

概要

JavaScriptで配列をループで処理する方法をまとめる。

環境

> node -v
v10.15.3

方法

for

汎用性が高い。記述量は多め。

const x = ['a', 'b', 'c']
for (let i = 0; i < x.length; i++) {
    console.log(`${i} : ${x[i]}`)
}
0 : a
1 : b
2 : c

forEach

値にしか興味がない場合。(n番目という情報は不要な場合)

const x = ['a', 'b', 'c']
x.forEach(v => console.log(v))
a
b
c

次の点に気をつける。

例外を throw する以外の方法で、forEach() ループを止めることはできません。ループ中に中断することがある場合、forEach() メソッドは適切な方法ではありません。

こういう場合は、forかfor...ofを使おう。

for...of

配列の値が返される。forEachとよく似ている。

const x = ['a', 'b', 'c']
for (let v of x) {
    console.log(v)
}
a
b
c

for...in

配列の要素にアクセス可能な値が返される。
ただし、下記のような注意点があるため、forやforEachを使うのが良さそう。

for...in はインデックスの順序が重要となる 配列 の繰り返しには使うぺきではありません。

const x = ['a', 'b', 'c']
for (let i in x) {
    console.log(`${i} : ${x[i]}`)
}
0 : a
1 : b
2 : c

stringが返るのが不思議な感じ。

const x = ['a', 'b', 'c']
for (let i in x) {
    console.log(`${i} : ${typeof i}`)
}
0 : string
1 : string
2 : string

個人的まとめ

配列のインデックスと値がどちらも必要 => for
値だけ必要 => forEach もしくは、for...of

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