LoginSignup
96
55

More than 1 year has passed since last update.

for ... of 文でインデックス(index)の値を使う方法

Last updated at Posted at 2018-04-26

JavaScriptでforループを使いたい時はfor...of文を使うのがES6になってからは定番になってました。

そんな中で通常のfor文ではいつも一緒にいたインデックスを表示したい事案があったのですが、やり方が分からず調べたのでまとめました。

イメージ的には以下のようにforループの中でインデックス番号を利用したい場合です。

const students = [
  { name: 'Taro', age: 26 },
  { name: 'Jiro', age: 24 },
  { name: 'Siro', age: 22 }
] 

for (let i = 0; i < students.length; i++) {
  console.log(`${i}: ${students[i].name}`)
}

// 0: Taro
// 1: Jiro
// 2: Siro

これをfor...ofで実現する時は、分割代入(destructuring)とObject.entries()を利用します。まずコードです。

for (const [index, student] of Object.entries(students)) {
  console.log(`${index}: ${student.name}`)
}

MDN 分割代入
MDN Object.entries

とか調べてたら遅いから素直にArray.forEach()使えって言われていました

students.forEach((student, index) => {
  console.log(`${index}: ${student.name}`)
})

結局これがベストなのか。

分割代入の使い所がいまいちわかっていなかったので、理解の助けにはなったとしてよしとしよう……

96
55
8

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
96
55