在下面的示例中,很容易理解生成器函数中的“ yield”。但是显然还有另一种“收益*”
function * loop(times){
while(times){
times--;
yield times;
}
}
let result = loop(2);
result.next() // {value: 1, done:false}
有人可以解释'yield'和'yield *'之间的区别吗?
答案 0 :(得分:1)
yield*
运算符将迭代委托给另一个可迭代的迭代器,如下所示:
// this function is more or less a no-op
function * iterate (iterable) {
yield * iterable;
}
function * loop (times) {
while (times) {
times--;
yield times;
}
}
console.log('accepts iterables');
for (const value of iterate([1, 2, 3])) {
console.log(value);
}
console.log('accepts generator iterators');
for (const value of iterate(loop(3))) {
console.log(value);
}
const iterator = [1, 2, 3][Symbol.iterator]();
// skip first value
iterator.next();
console.log('accepts partially consumed iterators');
for (const value of iterate(iterator)) {
console.log(value);
}