在Javascript中yield语句何时执行?

When does a yield statement get executed in Javascript?

本文关键字:何时 执行 语句 yield Javascript      更新时间:2023-09-26

我对JS 1.7的新yield特性中何时产生值有点困惑。

当我这样写函数时:

function helloWorld() {
    console.log('hello'); 
    yield "world";
} 
var sayHello = helloWorld();
sayHello.next();

它返回:

>"world"
>"hello"

但是当我这样写函数时:

function helloWorld() {
    console.log('hello'); 
    yield console.log("world");
}
var sayHello = helloWorld();
sayHello.next();

它返回:

>"hello"
>"world"
如我所愿

我很困惑为什么在第一种情况下"世界"在"你好"之前返回,也许我不明白yield是如何工作的,有没有人可能知道为什么yield会这样做?

对不起,这似乎是一个错误。

我试着在Firefox控制台使用yield,它输出了这个,但当我真正构建了一个实际的文件并在Firefox中运行它之后,它的行为与预期的一样

如果有人好奇

<html>
<head>
</head>
<body>
<script type="application/javascript;version=1.7" >
function helloWorld () {
    console.log("hello"); 
    yield "world";
    yield "END";
} 
var sayHello = helloWorld();
console.log(sayHello.next());
function helloWorld1 () {
    console.log('hello'); 
    yield console.log("world");
    yield "END2";
}
var sayHello1 = helloWorld1();
sayHello1.next();
console.log(sayHello.next());
console.log(sayHello1.next());
</script>
</body>
</html>

输出:

"你好"世界"你好"世界"结束"END2"