我正在编写生成器的简单函数
function simpleGenerator(){
yield "first";
yield "second";
yield "third";
};
var g = simpleGenerator();
console.log(g.next());
它给出了产量线 -
SyntaxError: missing ; before statement
我无法理解显示错误的原因...... 如果我使用返回
function simpleGenerator(x){
while(true){
var a=x*2;
return a;
}
}
var g = simpleGenerator(2);
console.log(g);
工作正常,
答案 0 :(得分:4)
必须像这样定义生成器函数
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,
扩展了函数语法以添加可选的*标记:
FunctionDeclaration: "function" "*"? Identifier "(" FormalParameterList? ")" "{" FunctionBody "}" FunctionExpression: "function" "*"? Identifier? "(" FormalParameterList? ")" "{" FunctionBody "}"
带*标记的函数称为生成函数。以下两个一元运算符仅允许在生成器函数的直接主体中(即,在主体中但不允许) 嵌套在另一个函数中):
AssignmentExpression: ... YieldExpression YieldExpression: "yield" ("*"? AssignmentExpression)?
如果在非生成函数中出现yield或yield *表达式,则会引发早期错误.YieldExpression: