LoginSignup
5
3

More than 3 years have passed since last update.

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

Last updated at Posted at 2019-08-22

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]"

一緒に参考にしたい記事

5
3
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
5
3