Published on

javascriptのfor-ofループでindexを使う方法

Authors
  • avatar
    Name
    ssu
    Twitter

javascriptのfor ofでindexを使う方法を紹介します。 2つのやり方があって、一つは単純に自分でカウントする方法です。

const letters = ['h', 'e', 'l', 'l', 'o'] let i = 0 for (const letter of letters) { console.log(`${i}番目のlettersは${letter}です`) i += 1 }

続いて、entries()を使う方法です。

const letters = ['h', 'e', 'l', 'l', 'o'] for (const [i, letter] of letters.entries()) { console.log(`${i}番目のlettersは${letter}です`) }

参考: Iterating with index and element

参考: Access to ES6 array element index inside for-of loop

参考: How to get the index of an iteration in a for-of loop in JavaScript