Iterator

作者: RQrry | 来源:发表于2020-04-09 00:06 被阅读0次

    遍历器

    是一种接口,为各种不同的数据结构提供统一的访问机制

    作用

    一是为各种数据结构,提供一个统一的、简便的访问接口;

    二是使得数据结构的成员能够按某种次序排列;

    三是 ES6 创造了一种新的遍历命令for...of循环,Iterator 接口主要供for...of消费。

    Iterator 的遍历过程

    (1)创建一个指针对象,指向当前数据结构的起始位置。也就是说,遍历器对象本质上,就是一个指针对象。

    (2)第一次调用指针对象的next方法,可以将指针指向数据结构的第一个成员。

    (3)第二次调用指针对象的next方法,指针就指向数据结构的第二个成员。

    (4)不断调用指针对象的next方法,直到它指向数据结构的结束位置。

    模拟遍历器

    /**
     * 模拟遍历器对象(指针对象)
     * @param {Array} arr
     */
    function myIterator (arr) {
      let index = 0;
      let len = arr.length;
      return {
        next () {
          return index<len ? 
            {value: arr[index++], done: false} : 
            {value: undefined, done:true};
        }
      }
    }
    
    let arr = [1,2,'a'];
    let it = myIterator(arr);
    console.log(it.next()); // { value: 1, done: false }
    console.log(it.next()); // { value: 2, done: false }
    console.log(it.next()); // { value: 'a', done: false }
    console.log(it.next()); // { value: undefined, done: true }
    console.log(it.next()); // { value: undefined, done: true }
    

    原生具备 Iterator 接口的数据结构

    一个数据结构只要部署了Symbol.iterator属性,就被视为具有 iterator 接口,就可以用for...of循环遍历它的成员。也就是说,for...of循环内部调用的是数据结构的Symbol.iterator方法。

    • Array
    • Map
    • Set
    • String
    • TypedArray
    • 函数的 arguments 对象
    • NodeList 对象

    相关文章

      网友评论

          本文标题:Iterator

          本文链接:https://www.haomeiwen.com/subject/libfmhtx.html