为什么ES6的“产量"很高?在这种情况下调用保留字? [英] Why is ES6 "yield" a reserved word when called in this context?

查看:67
本文介绍了为什么ES6的“产量"很高?在这种情况下调用保留字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用节点4.1.1.当我运行这段代码

I am using node 4.1.1. When I run this code

"use strict";

function *generator() {
  let numbers = [1,2,3,4,5];
  numbers.map(n => yield (n + 1));
}

for (var n of generator()) {
  console.log(n);
}

我收到此错误

  numbers.map(n => yield (n + 1));
                   ^^^^^

SyntaxError: Unexpected strict mode reserved word

如果我将代码重新排列为此

If I rearrange the code to be this

"use strict";

function *generator() {
  let numbers = [1,2,3,4,5];
  let higherNumbers = numbers.map(n => n + 1);
  for(let i=0;i<higherNumbers.length;i++) {
    yield higherNumbers[i];
  }
}

for (var n of generator()) {
  console.log(n);
}

我得到了预期的结果.

第二个为什么起作用,而第一个失败呢?可以肯定的是,如果关键字是保留关键字,那么它在所有上下文中都保留了,而不仅仅是在箭头函数中使用时?

Why does the second one work, and the first fail? And surely if a keyword is reserved, it's reserved in all contexts, not just when it's used in a arrow function?

推荐答案

这是因为箭头函数不是生成器函数.例如,

It is because arrow functions are not generator functions. For example,

function temp() {
  yield 1;
}

我们可以期望它起作用吗?否.因为temp不是生成器函数.箭头功能也是如此.

Can we expect this to work? No. Because temp is not a generator function. The same is applicable to arrow functions as well.

FWIW,根据ECMAScript 2015规范和

FWIW, the usage of yield in an Arrow function is an early error as per the ECMAScript 2015 specification, as per this section,

ArrowFunction:ArrowParameters => ConciseBody

  • 如果 ArrowParameters 包含 YieldExpression true ,则是语法错误.

  • It is a Syntax Error if ArrowParameters Contains YieldExpression is true.

如果 ConciseBody 包含 YieldExpression true ,则是语法错误.

It is a Syntax Error if ConciseBody Contains YieldExpression is true.

这篇关于为什么ES6的“产量"很高?在这种情况下调用保留字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆