JavaScript 生成器 - 如何在使用 .next() 调用时跳过 yield?

JavaScript Generators - How to skip yield when called using .next() ?

JavaScript 生成器允许您以程序方式生成操作。

是否有可能 skip/invoke 本地特定产量?

给定下面的例子,这是如何实现的?

我想产生值 1、3 和 5。

function *getVal() {
    yield 1;
    yield 2;
    yield 3;
    yield 4;
    yield 5;
} 


let x = getVal();

// I want to yield ONLY values 1 , 3 , & 5

// Here val will equal 1
let val = x.next();

// I now want to val to equal 3
val = << skip second yield and hit 3 >>

// Is it possible to skip a yield natively?
// ...

您可以随时调用下一个值而不赋值,然后再次调用 .next 并赋值:

function *getVal() {
    yield 1;
    yield 2;
    yield 3;
    yield 4;
    yield 5;
} 


let x = getVal();

let val = x.next().value;   // 1
console.log(val);           

x.next();
val = x.next().value;       // 3
console.log(val);

x.next();
val = x.next().value;       // 5
console.log(val);

这样你就忽略了一些产生的值。

生成器遵循 javascript iterator protocol,因此除了调用 next().

之外没有多少选项可以控制它们

但是,由于您可以控制生成器的逻辑,因此您可以为每个对 next() 的调用定义您想要的行为。如果您想跳过数字,只需设法将其传达给生成器即可。

比如这个生成器会生成连续的数字,但是会根据传入的数字跳过next()

function *getVal() {
    let n = 1;
    let skip = 0
    while (n <= 15){
        skip =  yield n
        n = n+1+ (skip || 0)
    }
} 


let x = getVal();

console.log(x.next().value);  // start with 1
console.log(x.next(1).value); // skip two
console.log(x.next().value)
console.log(x.next(2).value)  // skip 5 and 6
console.log(x.next(1).value); // skip 8
//etc.