for-in和for-of有什么区别
key和value
- for..in遍历得到key
const arr = [10, 20, 30, 40]
for (const key in arr) {
console.log(key)
}
- for..of遍历得到value
const arr = [10, 20, 30, 40]
for (const key of arr) {
console.log(key)
}
- 遍历对象:for..in可以,for..of不可以
- 遍历Map Set:for..of可以,for..in不可以
- 遍历generator:for..of可以,for..in不可以
- for..in 用于可枚举数据。如对象、数组、字符串,得到key
- for..of 用于可迭代数据、如数组、字符串、Map、Set,得到 value