[] 前没有分号会导致 JavaScript 错误 [英] No semicolon before [] is causing error in JavaScript

查看:24
本文介绍了[] 前没有分号会导致 JavaScript 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 引擎以 [a,b] 的长度调用 console.log,然后查看索引 [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 是一个字符串,str[a,b] 将解析为 str[b].正如 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 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆