Nic*_*ter 2 javascript yield generator next ecmascript-6
JavaScript 生成器允许您以程序方式生成操作。
是否可以在本地跳过/调用特定的产量?
鉴于以下示例,如何实现?
我想产生值 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?
// ...Run Code Online (Sandbox Code Playgroud)
生成器遵循 javascript迭代器协议,因此除了调用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.Run Code Online (Sandbox Code Playgroud)