发电机和“产量”在浏览器之外
此代码片段位于此处,在一篇描述 JavaScript 中的生成器和迭代器的 MDN 文章中。
function simpleGenerator(){
yield "first";
yield "second";
yield "third";
for (var i = 0; i < 3; i++)
yield i;
}
var g = simpleGenerator();
print(g.next()); // prints "first"
print(g.next()); // prints "second"
print(g.next()); // prints "third"
print(g.next()); // prints 0
print(g.next()); // prints 1
print(g.next()); // prints 2
print(g.next()); // StopIteration is thrown
在上面我们读到:
yield 关键字仅适用于封装在 HTML 中的代码块
<script type="application/javascript;version=1.7">
阻止(或更高版本)。
事实上,当嵌入 HTML 文件并包含在上述标记中时,该代码片段可以正常工作。问题是,我在 Rhino 中尝试过,它似乎无法在 HTML 和浏览器之外工作。
那么如何在浏览器之外使用生成器呢?
This is snippet is found here, in an MDN article describing generators and iterators in JavaScript.
function simpleGenerator(){
yield "first";
yield "second";
yield "third";
for (var i = 0; i < 3; i++)
yield i;
}
var g = simpleGenerator();
print(g.next()); // prints "first"
print(g.next()); // prints "second"
print(g.next()); // prints "third"
print(g.next()); // prints 0
print(g.next()); // prints 1
print(g.next()); // prints 2
print(g.next()); // StopIteration is thrown
Above that we read:
The yield keyword is only available to code blocks in HTML wrapped in a
<script type="application/javascript;version=1.7">
block (or higher version).
Indeed, the snippet works fine when embedded in an HTML file and included in the aforementioned tag. The problem is, I tried it in Rhino and it doesn't seem to work outside HTML and the browser.
So how can I use generators outside the browser?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
https://developer.mozilla.org/en/New_in_Rhino_1.7R1#JavaScript_1.7_features
https://developer.mozilla.org/en/New_in_Rhino_1.7R1#JavaScript_1.7_features
要更改上下文:
To change context: