es6的 yield

es6的 yield

 
 

你现在问的是 ES6 里的 yield,我会直接给你一个可上手的解释:它在 Generator 函数里用于“暂停并产出值”,然后可从暂停点继续执行。下面我会用最小示例说明 next、yield、yield* 和参数回传。

ES6 的 yield 是 Generator 的核心关键字。

  1. 只能在 Generator 函数里用
    写法是 function*,不是普通 function。

  2. 作用是“产出一个值并暂停函数”
    下次再调用 next() 时,从上次暂停的位置继续执行。

  3. next() 的返回结构
    每次 next() 都返回一个对象:

  • value: 当前产出的值
  • done: 是否执行结束

示例:

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 }

    1. yield 可以接收外部传回的值
      next(参数) 会把参数作为“上一个 yield 表达式的结果”。
 

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

  1. yield* 用于“委托”给另一个可迭代对象

    function* g1() {
    yield 1;
    yield 2;
    }
    function* g2() {
    yield 0;
    yield* g1();
    yield 3;
    }
    console.log([...g2()]); // [0, 1, 2, 3]

  2. 一句话记忆:
    yield = 暂停 + 产出,next = 恢复执行。

    如果你愿意,我可以再给你一版“ES6 yield 和 Python yield 的对照表”,看一次就能分清两者语法和行为差异。

posted on 2026-06-13 16:51  漫思  阅读(3)  评论(0)    收藏  举报

导航