es6-15 Iterator 和 for of 循环

Iterator

什么是 Iterator 接口

JS表示集合的对象主要有Array、Set、Object、Map,在以前,遍历它们需要使用2种不同的方法,而现在,JS提出了Iterator机制,可以给不同的数据结构提供统一的遍历方法,就是for…of。换句话说,只有部署了Iterator的数据才能用for…of遍历。

Iterator的遍历过程是这样的:

  1. 创建一个指针对象,指向当前数据结构的起始位置。也就是说,遍历器对象本质上,就是一个指针对象。
  2. 第一次调用指针对象的next方法,可以将指针指向数据结构的第一个成员。
  3. 第二次调用指针对象的next方法,指针就指向数据结构的第二个成员。
  4. 不断调用指针对象的next方法,直到它指向数据结构的结束位置。

每一次调用next方法,都会返回数据结构的当前成员的信息。具体来说,就是返回一个包含valuedone两个属性的对象。其中,value属性是当前成员的值,done属性是一个布尔值,表示遍历是否结束。

数据结构只要部署了 Iterator 接口,我们就成这种数据结构为“可遍历”(Iterable)。ES6 规定,默认的 Iterator 接口部署在数据结构的 Symbol.iterator 属性,或者说,一个数据结构只要具有 Symbol.iterator 数据,就可以认为是“可遍历的”(iterable)。
{
    let arr = ['hello', 'world']
    let map = arr[Symbol.iterator]()
    console.log(map.next()) // {value: "hello", done: false}
    console.log(map.next()) // {value: "world", done: false}
    console.log(map.next()) // {value: undefined, done: true}
}

可以供 for...of 消费的原生数据结构

  • Array
  • Map
  • Set
  • String
  • TypedArray(一种通用的固定长度缓冲区类型,允许读取缓冲区中的二进制数据)
  • 函数中的 arguments 对象
  • NodeList 对象
可以看上面的原生数据结构中并没有对象(Object),为什么呢?
那是因为对象属性的遍历先后顺序是不确定的,需要开发者手动指定。本质上,遍历器是一种线性处理,对于任何非线性的数据结构,部署遍历器接口就等于部署一种线性变换
做如下处理,可以使对象供 for...of 消费:
{
    // 自定义 Object iterator 接口
    let obj = {
        start: [1, 2, 3],
        end: [4, 5, 6],
        [Symbol.iterator](){
            let that = this
            let index = 0
            let arr = that.start.concat(that.end) // 数组合并
            let len = arr.length
            return {
                next () {
                    // 遍历过程
                    if (index < len) {
                        return {
                            value: arr[index++],
                            done: false // 继续循环
                        }
                    } else {
                        return {
                            value: arr[index++],
                            done: true // 终止循环
                        }
                    }
                }
            }
        }
    }
    // for of 验证是都能循环了
    for (let key of obj) {
        console.log(key) // 1 2 3 4 5 6
    }
}

没自定义 iterator 接口 Object 使用 for of 循环是会报错的

{
    let obj = {
        start: [1, 2, 3],
        end: [4, 5, 6],
    }
    for (let value of obj) {
        console.log(value) // TypeError: obj is not iterable
    }
}

调用 Iterator 接口的场合

解构赋值

{
    let set = new Set().add('a').add('b').add('c');
    let [x,y] = set;
    console.log(set) // Set(3) {"a", "b", "c"}
    console.log(x) // a
    console.log(y) // b
    let [first, ...rest] = set;
    console.log(first) // a
    console.log(rest) // ['b','c']
}

扩展运算符

{
    // 例一
    var str = 'hello';
    console.log([...str]) // ['h','e','l','l','o']
    // 例二
    let arr = ['b', 'c'];
    console.log(['a', ...arr, 'd']) // ['a', 'b', 'c', 'd']
}
原文地址:https://www.cnblogs.com/helzeo/p/11842575.html