for …in和for …of有什么区别?使用时的注意事项有哪些?为什么不建议用for …in遍历数组等数据结构?
for … in 循环返回的值都是数据结构的 键值名,遍历对象返回的对象的key值,遍历数组返回的数组的下标(key)
for … in 循环不仅可以遍历数字键名,还会遍历原型上的值和手动添加的其他键
const arr = ['a', 'b']
// 手动给 arr数组添加一个属性
arr.name = 'qiqingfu'
// for in 循环可以遍历出 name 这个键名
for (let i in arr) {
console.log(i)
// a
// b
// name
}
for of 循环用来获取一对键值对中的值
const arr = ['a', 'b', 'c']
// for in 循环
for (let i in arr) {
console.log(i)
// 0
// 1
// 2
}
// for of
for (let i of arr) {
console.log(i)
// a
// b
// c
}