javascript - Yield 显示语法错误;在 javascript 中缺失;

标签 javascript ecmascript-harmony

我在写生成器的简单函数

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/

相关文章:

javascript - 为什么使用 css3-mediaqueries.js 时我的 100% 宽元素会变成 30000px+ 宽?

javascript - ajax调用后表消失了

javascript - 浏览器如何区分ES5和ES6脚本?

javascript - 查找比较每个索引的多个数组的最大值

javascript - 如何为 React 游戏获取 cpu v cpu 函数

node.js - 默认情况下使用 --harmony-generators 编译 Node

javascript - ES6 Map 和 WeakMap 有什么区别?

javascript - Intellij Idea Ecmascript Harmony 模块语法

javascript - 可以在node.js/Javascript中拦截对模块或类的调用

javascript - 在不破坏 MVC 范式的情况下使用 ng-model (或其他解决方案)