- for...in 遍历得到key
- for...of 遍历得到value
代码
const arr = [1, 2, 3]
for (let val of arr) {
console.log(val);
}
const str = 'abc'
for (let c of str) {
console.log(c);
}
function fn() {
for (let arg of arguments) {
console.log(arg);
}
}
fn(100, 200, 300)
const pList = document.getElementsByTagName('p')
for (let p of pList) {
console.log(p)
}
适用于不同的数据类型
- 遍历对象: for...in 可以, for...of 不可以
- 遍历 Map Set : for...of 可以, for...in 不可以
- 遍历 generator : for...of 可以, for...in 不可以
const set = new Set([1, 2, 3])
for (let n of set) {
console.log(n)
}
const map = new Map([
['x', 100],
['y', 200],
['z', 300],
])
for (let n of map) {
console.log(n);
}
/* [ 'x', 100 ]
[ 'y', 200 ]
[ 'z', 300 ]
*/
function* foo() {
yield 10
yield 20
yield 30
}
for (let n of foo()) {
console.log(n); // 10 20 30
}
可枚举vs可迭代
可枚举:enumerable属性为true
可迭代:每个元素都有next方法
- for...in 用于可枚举数据, 如对象、数组、字符串
- for...of 用于可迭代数据, 如数组、字符串、Map、Set
答案
- for...in 用于枚举数据,如对象、数组、字符串,得到key
- for...of 用于可迭代数据,如数组、字符串、Map、Set,得到value