for in 和 for of

80 阅读1分钟

for in 和 for of的区别

  • for in 遍历得到 key
// 遍历数组
const arr = ["aa", "bb", "cc"];

for(let key in arr) {
    console.log(key); // 0 1 2
}

// 遍历对象
const obj = {name: "dj", age: 20};

for(let item in obj) {
    console.log(item); // name age
}

  • for of 遍历得到 value
// 遍历数组
const arr = ["aa", "bb", "cc"];

for(let value of arr) {
    console.log(value); // aa bb cc
}

// 遍历字符串
const str = "abc";

for(let i of str) {
    console.log(i); // a b c
}

// 遍历参数
function fn() {
    for(let arg of arguments) {
        console.log(arg); // a b c
    }
}

fn("a", "b", "c");

// 遍历dom节点
const domList = document.querySelectorAll("p");
for(let dom of domList) {
    console.log(dom); // p p p
}

// 遍历 set
const set = new Set([10, 20, 30]);
for(let s of set) {
    console.log(s); // 10 20 30
}

// 遍历 map
const map = new Map([
    ['x', 100],
    ['y', 200],
])

for(let m of map) {
    console.log(m); // ['x', 100]  ['y', 200]
}

// 遍历 generator
const map = new Map([
    ['x', 100],
    ['y', 200],
])

for(let m of map) {
    console.log(m); // ['x', 100]  ['y', 200]
}

使用与不同的数据类型

  • 遍历对象

for in 可以,for of 不可以

  • 遍历 Map Set

for of 可以,for in 不可以

  • 遍历 generator

for of 可以,for in 不可以

可枚举 vs 可迭代

  • for in 用于可枚举的数据,如数组、对象、字符串

  • for of 用于可迭代的数据,如数组、字符串、Map、Set