alert("There will be an error")
[1, 2].forEach(alert)Run Code Online (Sandbox Code Playgroud)
现在,如果我运行代码,则仅显示第一个警报,然后出现错误!我知道为什么会有错误(没有自动分号插入),但是我不明白错误消息:Uncaught TypeError:无法读取未定义的属性“ 2”。JavaScript解释器如何读取此代码?
如果有<expression>[...],解释器将尝试在上查找属性expression。当方括号内包含逗号时,您将调用逗号运算符,该运算符的值将为列表中最后一项的值。所以
foo[1, 2]
Run Code Online (Sandbox Code Playgroud)
相当于
foo[2]
Run Code Online (Sandbox Code Playgroud)
这就是这里正在发生的事情:
foo[1, 2]
Run Code Online (Sandbox Code Playgroud)
相当于
相当于
alert("There will be an error")
[1, 2].forEach(alert)Run Code Online (Sandbox Code Playgroud)
等同于(无alert消息)
alert("There will be an error")
[2].forEach(alert)Run Code Online (Sandbox Code Playgroud)
这就是“ 2”的来源。alert返回undefined,因此错误消息为Uncaught TypeError: Cannot read property '2' of undefined。
该[1, 2]不会没有得到评估作为一个数组,即使它看起来像一个样。