LoginSignup
0
0

More than 3 years have passed since last update.

【JavaScript】for-ofとfor-inの違い

Last updated at Posted at 2020-12-07

for-ofとfor-in

どっちがどっちかわからなくなるときがあるのでメモ

for-of

配列の要素の繰り返しに特化している

namesを一つずつnameに代入する。

main.js
const names = ['田中', '山田', '佐藤', '井上'];

for (const name of names) {
  console.log(name);
}

// 田中
// 山田
// 佐藤
// 井上

また、for-ofでは分割代入と同じ記述が使用でき、複雑な構造を持つ配列から
必要な要素だけを取り出すことができる。

main.js
const personInfo = [
  { name: '田中', age: 22 },
  { name: '山田', age: 21 },
  { name: '佐藤', age: 24 },
  { name: '井上', age: 20 },
];

for (const { age } of personInfo) {
  console.log(age);
}

// 22
// 21
// 24
// 20

for-if

オブジェクトの各プロパティの値に対する繰り返しに特化している。

personInfoプロパティ名を一つずつinfoに代入している

main.js
const personInfo = {
  name: '田中',
  age: 22,
  height: 170,
}

for (const info in personInfo) {
  console.log(`${info} : ${personInfo[info]}`);
}

// name : 田中
// age : 22
// height : 170

配列に対してはindexを代入する。
namesindexを一つずつnameに代入している

main.js
const names = ['田中', '山田', '佐藤', '井上'];

for (const name in names) {
  console.log(name);
}


// 0
// 1
// 2
// 3
0
0
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
0
0