【问题标题】:Create an iterator with a next method that returns each value of the array when .next is called使用 next 方法创建一个迭代器,该方法在调用 .next 时返回数组的每个值
【发布时间】:2020-04-17 00:03:49
【问题描述】:

我正在尝试实现一个迭代器函数,它基本上只是 JS 中的一个闭包。

我已经能够通过调用iteratorWithNext() 列出数组的每个值,但是我对接下来如何实现函数感到困惑

下面是我想出的,但是当我打电话给iteratorWithNext()时,我得到了一个TypeError: iteratorWithNext.next is not a function

function nextIterator(arr) {
    let count = 0
    function next(){return count++}
    return next
}

const array3 = [1, 2, 3];
const iteratorWithNext = nextIterator(array3);

以下是所需的输出:

console.log(iteratorWithNext.next()); // -> should log 1
console.log(iteratorWithNext.next()); // -> should log 2
console.log(iteratorWithNext.next()) // -> should log 3

【问题讨论】:

  • 迭代器需要.value 来获取值。你想要自己的(不同的)风格吗?
  • (具体指出答案的不同之处:return next,返回函数,变成return { next },返回一个带有next属性的对象,即函数。)

标签: javascript arrays methods iterator closures


【解决方案1】:

使用next 方法返回一个对象字面量:

function nextIterator(arr) {
  let count = 0

  function next() {
    return arr[count++]
  }
  
  // return an object literal with the next method
  return {
    next
  }
}

const array3 = [1, 2, 3];
const iteratorWithNext = nextIterator(array3);

console.log(iteratorWithNext.next()); // -> should log 1
console.log(iteratorWithNext.next()); // -> should log 2
console.log(iteratorWithNext.next()) // -> should log 3

【讨论】:

  • 我忘记包含函数 nextIterator 的参数 arr 和调用 nextIterator() 的参数 array3。 const array3 发生了什么? nextIterator 的参数怎么不用array3?
  • 查看更新的答案。请注意,这不遵循标准的 JS 迭代器协议(您需要返回一个对象 { value: any, done: bool }。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-19
  • 2021-11-01
  • 2015-05-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-18
  • 2020-12-30
相关资源
最近更新 更多