我正在尝试实现一个迭代器函数,该函数基本上只是JS中的闭包。
我已经能够通过调用列出数组的每个值iteratorWithNext()
,但是我对下一步如何实现函数感到困惑
以下是我想出的内容,但是TypeError: iteratorWithNext.next is not a function
当我打电话时iteratorWithNext()
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
使用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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句