for in | for in 比较 解释 | 以后找知识点先从这里面搜索

    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 报错了
    }

---> 说明 for in 可以打印出对象, for of 不能打印出对象

    const arr = ['a', 'b', 'c']
    // for in 循环
    for (let i in arr) {
        console.log(i)
        // 0
        // 1
        // 2
    }
-----------------》 说明for in 就是 key


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

--> for of 数组没有毛病


总结一句: for in 循环特别适合遍历对象。

 

  • for of 循环用来获取一对键值对中的值,而 for in 获取的是 键名

  • 一个数据结构只要部署了 Symbol.iterator 属性, 就被视为具有 iterator接口, 就可以使用 for of循环。

    例1这个对象,没有 Symbol.iterator这个属性,所以使用 for of会报 obj is not iterable

  • for of 不同与 forEach, 它可以与 break、continue和return 配合使用,也就是说 for of 循环可以随时退出循环。

  • 提供了遍历所有数据结构的统一接口

只要有 iterator 接口的数据结构,都可以使用 for of循环。

  • 数组 Array
  • Map
  • Set
  • String
  • arguments对象
  • Nodelist对象, 就是获取的dom列表集合

以上这些都可以直接使用 for of 循环。 凡是部署了 iterator 接口的数据结构也都可以使用数组的 扩展运算符(...)、和解构赋值等操作。

http://www.fly63.com/article/detial/1444

原文地址:https://www.cnblogs.com/qinqiu/p/13032050.html