所以有一些方法可以在循环中停止生成器for of
,但是如何break
向生成器发送信号(与 in 相比return
)for-of
?
请考虑代码。
例如,前面的代码只是将一个值从 1 增加到 10 ,并在两者之间进行暂停和恢复。
function *Generator() {
try {
var nextValue;
while (true) {
if (nextValue === undefined) {
nextValue = 1;
}
else {
nextValue++;
}
yield nextValue;
}
}
// cleanup clause
finally {
console.log( "finally has been reached." );
}
}
它通过使用循环10次for of
:
var it = Generator();// it gets Generator's iterator
for (var v of it) {
console.log(v);
if (v > 9) {
//it.return("stop");//this is another tool for stopping, but it doesn't stop immediately.
break;
console.log("it won't run");//this line won't run
}
}
顺便it.return()
说一句,实现的 clear(it
是主 Object 并获得了控制权,但是break
?);