[英]Generators and “yield” outside the browser
這是片斷被發現在這里 ,一個MDN文章描述的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
在上面我們讀到:
yield關鍵字僅適用於包含在HTML中的HTML中的代碼塊
<script type="application/javascript;version=1.7">
塊(或更高版本)。
實際上,當嵌入HTML文件並包含在上述標簽中時,該片段工作正常。 問題是,我在Rhino中嘗試過,它似乎不能在HTML和瀏覽器之外工作。
那么如何在瀏覽器之外使用生成器呢?
https://developer.mozilla.org/en/New_in_Rhino_1.7R1#JavaScript_1.7_features
要啟用JavaScript 1.7支持,必須使用
Context.setLanguageVersion()
API調用將版本設置為170。 如果您使用的是Rhino shell,則可以在命令行中指定-version 170
,或者在shell執行的代碼中調用version(170)
。
要改變背景:
Context ctx = Context.enter();
ctx.setLanguageVersion(Context.VERSION_1_7);
try {
CompilerEnvirons compEnv = new CompilerEnvirons();
compEnv.initFromContext(ctx);
...
}
finally { Context.exit(); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.