forin和forof的区别

97 阅读1分钟
forin 遍历 key,forof 遍历 value
let arr = ['a','b','c']

for(const i in arr){
  console.log(i)
}
//0,1,2

for(const i of arr){
  console.log(i)
}
//a,b,c
forin会遍历自身的属性和原型的属性,forof只会遍历自身的属性
let arr = ['a','b','c']

Array.prototype.test = 'str test'

for(const i in arr){
  console.log(i)
}
//0,1,2,test

for(const i of arr){
  console.log(i)
}
//a,b,c
forof只能遍历实现了iterator接口的数据
let arr = ['a','b','c']
let obj = {
  key1:'str key1',
  key2:'str key2'
}

for(const i of arr){
  console.log(i)
}
//a,b,c

for(const i of obj){
  console.log(i)
}
//Uncaught TypeError: obj is not iterable
//对象不具有iterator接口