javascript - 箭头函数表达式与普通函数表达式的自动分号插入 (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 中的箭头函数有例外吗?还是我错过了什么?
解决方案
规范说:
当从左到右解析源文本时,遇到任何语法生成都不允许的标记(称为违规标记)时,如果一个或多个以下条件为真:[...]
因此,要发生 ASI,如果没有它,语法可能是无效的产生式。实际上它是:
() => {}[0] // syntax error
所以这里需要分号。现在为什么这是一个语法错误,而function () { }[0]
不是?那么,成员访问定义为
MemberExpression:
MemberExpression [ Expression ]
PrimaryExpression
//...
PrimaryExpression:
FunctionExpression
// no arrow function here
为什么语法是这样的?我不知道。
推荐阅读
- sql - 如何计算外键并使用它对主表进行排序?
- android - FusedLocationProviderClient 总是报告 LocationAvailability false
- javascript - SVG 反转颜色
- c++ - 如何将给定的代码转换为数学函数?
- julia - 如何在 Julia 中裁剪图像?
- r - 在 R 中创建邻接矩阵
- javascript - javascript fetch - SAMLResponse 的自动表单提交
- python - 在 Pandas 中仅移动选定的行
- vue.js - vue axios.get 从 imgur 获取图像
- react-hooks - 使用覆盖其他组件样式的 react-planet 时组件中有多个 jss