【发布时间】: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