问题描述
var a = [1,2,3,4];
var b = [10,20,30,40];
console.log([a,b].length)
[a,b].some(function(x){ x.push(x.shift()) });
今天这个代码导致我非常惊讶
I was extremely surprised today when this code caused
[a,b].some(function(x){ x.push(x.shift()) });
^
TypeError: Cannot call method 'some' of undefined
显然JavaScript'自动分号插入'在这里没有按预期工作。但是为什么?
Obviously the JavaScript 'auto semicolon insertion' is not working as expected here. But why?
我知道你可能会建议在任何地方使用;
以避免类似的事情,但问题是不管是否更好地使用;
。我很想知道这里究竟发生了什么?
I know you might recommend to use ;
everywhere to avoid something like that, but the question is not about whether it is better to use ;
or not. I would love to know what exactly happens here?
推荐答案
当我担心分号插入时,我想到了什么线条有问题的看起来没有任何空格。在你的情况下,那将是:
When I'm worried about semicolon insertion, I think about what the lines in question would look like without any whitespace between them. In your case, that would be:
console.log([a,b].length)[a,b].some(function(x){ etc });
这里你告诉Javascript引擎调用 console.log
,长度为 [a,b]
,然后查看索引 [a,b]
该调用的结果。
Here you're telling the Javascript engine to call console.log
with the length of [a,b]
, then to look at index [a,b]
of the result of that call.
console.log
返回一个字符串,因此您的代码将尝试查找属性 b
该字符串未定义,并且对 undefined.some()
的调用失败。
console.log
returns a string, so your code will attempt to find property b
of that string, which is undefined, and the call to undefined.some()
fails.
有趣的是, str [a,b]
将解析为 str [b]
假设str是一个字符串。正如Kamil指出的那样, a,b
是一个有效的Javascript表达式,该表达式的结果只是 b
。
It's interesting to note that str[a,b]
will resolve to str[b]
assuming str is a string. As Kamil points out, a,b
is a valid Javascript expression, and the result of that expression is simply b
.
这篇关于在[]导致Javascript错误之前没有分号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!