我在写生成器的简单函数
function simpleGenerator(){
yield "first";
yield "second";
yield "third";
};
var g = simpleGenerator();
console.log(g.next());
它正在为 yield 线付出--
SyntaxError: missing ; before statement
我无法得到显示错误的原因... 如果我像这样使用返回
function simpleGenerator(x){
while(true){
var a=x*2;
return a;
}
}
var g = simpleGenerator(2);
console.log(g);
一切正常,
最佳答案
生成器函数必须这样定义
function * simpleGenerator() { # Note the `*` after `function` keyword
yield "first";
yield "second";
yield "third";
};
var g = simpleGenerator();
console.log(g.next());
# { value: 'first', done: false }
引自ECMA 6's Harmony page for Generator functions ,
The function syntax is extended to add an optional * token:
FunctionDeclaration: "function" "*"? Identifier "(" FormalParameterList? ")" "{" FunctionBody "}" FunctionExpression: "function" "*"? Identifier? "(" FormalParameterList? ")" "{" FunctionBody "}"
A function with a * token is known as a generator function. The following two unary operators are only allowed in the immediate body of a generator function (i.e., in the body but not nested inside another function):
AssignmentExpression: ... YieldExpression YieldExpression: "yield" ("*"? AssignmentExpression)?
An early error is raised if a yield or yield* expression occurs in a non-generator function.YieldExpression:
关于javascript - Yield 显示语法错误;在 javascript 中缺失;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23488034/