for in 和 for of

2022-08-03  本文已影响0人  回不去的那些时光

for in 和 for of的区别

// 遍历数组
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
}
// 遍历数组
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]
}

使用与不同的数据类型

可枚举 vs 可迭代

上一篇 下一篇

猜你喜欢

热点阅读