【问题标题】:How to make custom iterator interface iterable in JavaScript如何使自定义迭代器接口在 JavaScript 中可迭代
【发布时间】:2020-04-15 17:20:59
【问题描述】:

我有一个数组,并且我已经覆盖了它的默认迭代器行为。问题是,在覆盖之后,返回的迭代器变得不可迭代,并且 for..of..loop 在它上面失败但在数组上工作,但是对数组的迭代器 next() 方法的显式调用仍然有效。下面是代码:

let arr = ["A", "B", "C", "D", "E", "F"];
arr[Symbol.iterator] = function(){
  let i = 0;

  return {
    //Iterator interface
    next:function(){
      //IteratorResult Interface
      return {
        value: arr[i++]+"..",
        done: arr[i] == undefined?true:false
      }
    }
  }
}

这里是迭代器对象

let arrIterator = arr[Symbol.iterator](); //An iterator object returned but not iterable

在迭代器对象上使用 for..of..loop 进行消费试验

for (let i of arrIterator){
  console.log(i);
}

输出

在数组上使用 for..of..loop 进行消费试验

for (let i of arr){
  console.log(i);
}

输出

显式调用 next() 方法的消费试验

console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());
console.log(arrIterator.next());

输出

我真的很想知道如何使自定义迭代器可迭代以供 for..of..loop 使用。

谢谢

【问题讨论】:

    标签: javascript iterator


    【解决方案1】:

    您还需要实现 Iterable 协议(而不仅仅是 Iterator

    [Symbol.iterator]: function() { return this; } 添加到您的 Iterator 对象中,它会起作用。

    let arr = ["A", "B", "C", "D", "E", "F"];
    arr[Symbol.iterator] = function() {
      let i = 0;
    
      return {
        //Iterator interface
        next: function() {
          //IteratorResult Interface
          return {
            value: arr[i++] + "..",
            done: arr[i] == undefined ? true : false
          }
        },
        // Iterable interface
        [Symbol.iterator]: function() {
          return this;
        }
      }
    }
    
    let arrIterator = arr[Symbol.iterator](); //An iterator object returned but not iterable
    
    for (let i of arrIterator) {
      console.log(i);
    }

    更多信息请见Iteration protocols

    【讨论】:

      猜你喜欢
      • 2010-11-25
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 2016-06-18
      • 1970-01-01
      • 2015-02-04
      • 2021-12-26
      相关资源
      最近更新 更多