• for...of为什么不能遍历Object对象


    因为能够被for...of正常遍历的,都需要实现一个遍历器Iterator。而数组、字符串、Set、Map结构,早就内置好了Iterator(迭代器),它们的原型中都有一个Symbol.iterator方法,而Object对象并没有实现这个接口,使得它无法被for...of遍历。例如:
    如下:

    
    Array.prototype[Symbol.iterator];
     
    // ƒ values() { [native code] }
     
    String.prototype[Symbol.iterator];
     
    // ƒ [Symbol.iterator]() { [native code] }
     
    Set.prototype[Symbol.iterator];
     
    // ƒ values() { [native code] }
     
    Map.prototype[Symbol.iterator];
     
    // ƒ entries() { [native code] }
     
    Object.prototype[Symbol.iterator];
     
    // undefined
    

    如何让对象可以被for of 遍历,当然是给它添加遍历器,代码如下:

    
          Object.prototype[Symbol.iterator] = function() {
            let index = 0;
            let arr = Object.entries(this);
            let length = arr.length;
            return {
              next: () => {
                let key = arr[index] && arr[index][0];
                let text = arr[index] && arr[index][1];
                let value = { [key]: text };
                let done = index >= length;
                index++;
                return { value, done };
              }
            };
          };
    ————————————————
    

    修改下 补充说明一下如何使用生成器实现遍历,代码如下:

     Object.prototype[Symbol.iterator] = function*() {
            let index = 0;
            let arr = Object.entries(this);
            let length = arr.length;
            while (true) {
                if (index >= length) {
                    return false
                } else {
                    let key = arr[index] && arr[index][0];
                    let text = arr[index] && arr[index][1];
                    let value = { [key]: text };
                    index++;
                    yield value
                }
            }
          };
    

    ES6 迭代器

    原文链接:

    爱生活、爱编程!
  • 相关阅读:
    iOS-申请开发证书流程
    iOS-代理
    进程和线程
    iOS单例模式
    Switch语句
    枚举类型
    程序的三种结构
    运算符
    Swift项目开发中的一些必备数据
    Swift开发中常用的一些图片处理方法
  • 原文地址:https://www.cnblogs.com/liliuyu/p/14631179.html
Copyright © 2020-2023  润新知