| forEach, for of (繰り返し - 配列)


forループ以外で配列の中身をそれぞれ取り出したい時

const bmth = ["bring", "me", "the", "horizon"];

期待する出力結果

"0 - bring"
"1 - me"
"2 - the"
"3 - horizon"

forEach()


bmth.forEach((item, index)=>{
  console.log(`${index} - ${item}`)
})

for of


for( let [index, item] of bmth.entries()){
  console.log(`${index} - ${item}`)
}

* indexいらない、各要素だけ欲しい時


for (let item of bmth) {
  console.log(item)
}

// 期待する出力結果
// "bring"
// "me"
// "the"
// "horizon"

for of (オブジェクトに対して)

JavaScriptでいうオブジェクトってRubyでいうハッシュ的な
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Object

// オブジェクトを用意
const myProfile = {
  name: "Yo",
  age: 26,
  "my fav":[{
    album: "amo", 
    song: "sugar honey ice & tea"
  },{
    album: "suicide season", 
    song: "diamonds aren't forever"
  }]
};
for (let prop of Object.keys(myProfile)) {
  console.log(`key: ${prop} - value: ${myProfile[prop]}`);
}
// 期待する出力結果

"key: name - value: Yo"
"key: age - value: 26"
"key: my fav - value: [object Object],[object Object]"

一緒に参考にしたい記事