我正在学习迭代器/生成器,想知道是否有一种方法可以使迭代器重新启动?比如在调用最后一个 .next()
后是否有一种方法可以使它重新开始?
function nextName() {
const current = names.next().value
const output = document.querySelector("output")
if (current) {
output.innerText = current.name
}
else {
// code to reset it! currently I'm just displaying text
output.innerText = 'Nothing left'
}
}
function nameIterator(names) {
let nextIndex = 0;
return {
next: function() {
return nextIndex < names.length ?
{ value: names[nextIndex++], done: false } :
{ done: true }
}
}
}
这里有一个codepen示例,以便更清楚地了解:https://codepen.io/sammiepls/pen/romyKL?editors=1010 所以当您点击按钮时,它会调用我的迭代器,每次单击时都会显示我的名称数组中的一个名称。如何使其在最后一次单击时重置,以便返回第一个名称?
因此,显示将如下所示:
Bob
Peter Sally
Bob // 再次获取 Bob
在codepen中,我还使用生成器编写了迭代器,是否有任何方法可以在遍历完数组后将其重置回第一个位置?