简体   繁体   English

为什么这段代码不会在JavaScript中引发错误?

[英]Why doesn't this piece of code throw an error in JavaScript?

It took me a while to find this problem in my code when it stopped working. 当它停止工作时,我花了一段时间才在我的代码中发现了这个问题。

console.log('before var');
var lastReview = ''
    newReview;
console.log('after var');

There is no comma after lastReview = '' which I believe is a syntax error, however both Chrome inspector and Firebug report nothing in the console. lastReview = ''之后没有逗号,我认为这是语法错误,但是Chrome检查器和Firebug在控制台中lastReview = ''报告任何内容。 The following code console.log simply is never executed. 以下代码console.log根本不会执行。

Chrome actually reports the error if you run the snippet directly in the console... but not when the actual page runs. 如果您直接在控制台中运行代码段,则Chrome实际上会报告错误...但是在实际页面运行时却不会。 Firefox does not report an error in any case. Firefox在任何情况下均不会报告错误。

Why don't the dev tools report these kinds of simple problems? 开发工具为什么不报告这些简单的问题?

There is no (syntax) error - this code is valid javascript. 没有(语法)错误-此代码是有效的javascript。 According to the rules , JS inserts a semicolon: 根据规则 ,JS插入分号:

console.log('before var');
var lastReview = ''; <-- here
    newReview;
console.log('after var');

so that newReview; 这样newReview; becomes a valid, albeit nonsensical, statement. 成为有效的(尽管毫无意义的)陈述。

Although there's no syntax error, this code still throws a runtime error due to undefined variable (assuming newReview wasn't declared before). 尽管没有语法错误,但是由于未定义变量,此代码仍会引发运行时错误(假设newReview未声明newReview )。

Because semi-colons are automatically inserted anyway if missing - so there is no syntax error in the code. 因为分号会自动插入(如果丢失),因此代码中没有语法错误。

Read more about this here in the Rules of Automatic Semicolon Insertion section of the ECMAScript Language Specification. 在ECMAScript语言规范的“自动分号插入规则”部分中,请阅读有关此内容的更多信息。

In your example, this: 在您的示例中,这是:

var lastReview = ''

becomes: 变成:

var lastReview = '';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM