























你现在问的是 ES6 里的 yield,我会直接给你一个可上手的解释:它在 Generator 函数里用于“暂停并产出值”,然后可从暂停点继续执行。下面我会用最小示例说明 next、yield、yield* 和参数回传。
ES6 的 yield 是 Generator 的核心关键字。
只能在 Generator 函数里用
写法是 function*,不是普通 function。
作用是“产出一个值并暂停函数”
下次再调用 next() 时,从上次暂停的位置继续执行。
next() 的返回结构
每次 next() 都返回一个对象:
示例:
function* gen() {
yield 1;
yield 2;
return 3;
}
const it = gen();
console.log(it.next()); // { value: 1, done: false }
console.log(it.next()); // { value: 2, done: false }
console.log(it.next()); // { value: 3, done: true }
console.log(it.next()); // { value: undefined, done: true }
function* gen() {
const a = yield "first";
console.log("a =", a);
const b = yield "second";
console.log("b =", b);
}
const it = gen();
console.log(it.next()); // first
console.log(it.next(100)); // second,且 a = 100
console.log(it.next(200)); // done true,且 b = 200
function* g1() {
yield 1;
yield 2;
}
function* g2() {
yield 0;
yield* g1();
yield 3;
}
console.log([...g2()]); // [0, 1, 2, 3]
一句话记忆:
yield = 暂停 + 产出,next = 恢复执行。
如果你愿意,我可以再给你一版“ES6 yield 和 Python yield 的对照表”,看一次就能分清两者语法和行为差异。
漫思
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。