- for…in 语句用于遍历数组或者对象的属性(对数组或者对象的属性进行循环操作)。
- for in得到对对象的key或数组,字符串的下标
- for of和forEach一样,是直接得到值
- for of不能用于对象
1.两者对比例子(遍历对象)
const obj = {
a: 1,
b: 2,
c: 3
}
for (let i in obj) {
console.log(i) //输出 : a b c
}
for (let i of obj) {
console.log(i) //输出: Uncaught TypeError: obj is not iterable 报错了
}
2.两者对比例子(遍历数组)
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
}
for of 不同与 forEach, 它可以与 break、continue和return 配合使用,也就是说 for of 循环可以随时退出循环。