LoginSignup
0
0

More than 1 year has passed since last update.

【Javascript】for...inとfor...ofの違い

Posted at

for...in

  • オブジェクトのプロパティを列挙するためのループ処理。
  • 対象のオブジェクトが持つメソッド以外にも、外部から追加したプロトタイプも列挙する。
const tom = {
  name: 'Tom',
  age: 23
}
const like = {
  food: 'potato',
  animal: 'cat'
}

Object.setPrototypeOf(tom, like)

for(let key in tom) {
  console.log(`${key}: ${tom[key]}`)
}

tomのプロトタイプにlikeのメソッドを設定すると、ループ処理で呼び出される。

コンソール
name: Tom
age: 23
food: potato
animal: cat

for...of

  • イテラルオブジェクトの値を列挙するループ処理。
  • 配列やMap、Set、文字列、NodeListなどの反復可能オブジェクトから要素を取り出すために使用される。
  • オブジェクトのプロパティは列挙されない。
const array = [1, 2, 3];

for(let val of array) {
  console.log(val)
}
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