当我在 MDN 中阅读迭代器和生成器时。我在那里读了一些段落,但我不明白这到底是什么意思?任何人都可以帮助我这一段到底是什么意思?
It may be possible to iterate over an iterable more than once, or only once. It is up to the programmer to know which is the case. Iterables which can iterate only once (e.g. Generators) customarily return this from their @@iterator method, where those which can be iterated many times must return a new iterator on each invocation of @@iterator.
最佳答案
看看这个例子:
function iterateTwice(iterable) {
for (const x of iterable) console.log(1, x);
for (const x of iterable) console.log(2, x);
}
console.log("array");
const array = ['a', 'b', 'c'];
iterateTwice(array);
console.log("generator");
function* makeGenerator() {
yield 'a'; yield 'b'; yield 'c';
}
const generator = makeGenerator();
iterateTwice(generator);
这是因为每次从头到尾迭代数组时,array[Symbol.iterator]()
都会返回一个新的迭代器,而generator[Symbol.iterator]()
每次都返回相同的迭代器对象[1]。第一个 for … of
迭代确实耗尽了它,第二个循环将看到并结束不产生任何项目的迭代器。
1:实际上是它自己,generator === generator[Symbol.iterator]()
。
关于javascript - 生成器和迭代器 - 可迭代 [MDN 文档],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58573790/