不存在的分号

时间:2019-07-11 11:24:41

标签: javascript

alert("There will be an error")
[1, 2].forEach(alert)

现在,如果我运行代码,则仅显示第一个警报,然后出现错误!我知道为什么会有错误(没有自动分号插入),但是我不明白错误消息:  Uncaught TypeError:无法读取未定义的属性“ 2”。 JavaScript解释器如何读取此代码?

2 个答案:

答案 0 :(得分:7)

当您拥有<expression>[...]时,解释器将尝试在expression上查找属性。当方括号内包含逗号时,您正在调用comma operator,其结果为列表中最后一项的值。所以

foo[1, 2]

等同于

foo[2]

这正是这里发生的事情:

alert("There will be an error")
[1, 2].forEach(alert)

等同于

alert("There will be an error")
[2].forEach(alert)

等同于

alert("There will be an error")[2].forEach(alert)

等于(没有alert消息)

undefined[2].forEach(alert)

这就是“ 2”的来源。 alert返回undefined,因此错误消息为Uncaught TypeError: Cannot read property '2' of undefined

[1, 2]不会不会被评估为数组,即使它看起来像一个。

答案 1 :(得分:0)

如果您在每行的末尾编写不带分号的JS,则有时您可能会抱怨:

rax = rdx = 0x28 | 0x12 | 0x30 | 0x34 | <--- rsp 0x38 | 0x56 | 0x40 | 0x78 | 0x48 | 0x9A | movq %rsp, %rax rax = 0x30 rdx = 0x28 | 0x12 | 0x30 | 0x34 | <--- rsp 0x38 | 0x56 | 0x40 | 0x78 | 0x48 | 0x9A | pushq %rsp ;store, using rsp as the address, then subtract 8 from rsp rax = 0x30 rdx = 0x28 | 0x12 | <--- rsp 0x30 | 0x30 | 0x38 | 0x56 | 0x40 | 0x78 | 0x48 | 0x9A | popq %rdx ;load, using rsp as the address, then add 8 to the rsp rax = 0x30 rdx = 0x30 0x28 | 0x12 | <--- rsp 0x30 | 0x30 | 0x38 | 0x56 | 0x40 | 0x78 | 0x48 | 0x9A | subq %rdx, %rax ;Return 0 rax = 0x00 rdx = 0x30 0x28 | 0x12 | 0x30 | 0x30 | <--- rsp 0x38 | 0x56 | 0x40 | 0x78 | 0x48 | 0x9A | [或任何算术运算符(+-*

此处进一步说明:https://medium.com/@goatslacker/no-you-dont-need-semicolons-148d936b9cf2

因此,您可以通过将数组定义为变量来避免这种情况。

/