首页 > 解决方案 > 箭头函数表达式与普通函数表达式的自动分号插入 (ASI)

问题描述

const log = function (x)
{
	console.log(x);
}
[1,2,3,4,5].forEach(num=>log(num))

这会引发错误:-

{
  "message": "Uncaught TypeError: Cannot read property 'forEach' of undefined",
  "filename": "https://stacksnippets.net/js",
  "lineno": 16,
  "colno": 13
}

这是因为数组前缺少分号。所以它被误解为:-

const log = function (x)
{
    console.log(x);
}[1,2,3,4,5].forEach(num=>log(num))

但为什么以下工作: -

const log = (x)=>{
	console.log(x)
}
[1,2,3,4,5].forEach(num=>log(num))

我知道它也是一个函数表达式。ASI 中的箭头函数有例外吗?还是我错过了什么?

标签: javascript

解决方案


规范说:

当从左到右解析源文本时,遇到任何语法生成都不允许的标记(称为违规标记)时,如果一个或多个以下条件为真:[...]

因此,要发生 ASI,如果没有它,语法可能是无效的产生式。实际上它是:

  () => {}[0] // syntax error

所以这里需要分号。现在为什么这是一个语法错误,而function () { }[0]不是?那么,成员访问定义为

  MemberExpression:
    MemberExpression [ Expression ]
    PrimaryExpression
    //...

 PrimaryExpression:
   FunctionExpression
   // no arrow function here

为什么语法是这样的?我不知道。


推荐阅读