本文介绍了为什么在使用分号时不将此JavaScript解释为代码块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Chrome版本^72中,如果我运行以下JavaScript,则没有错误.

In Chrome version ^72 if I run the following JavaScript there are no errors.

{ prop: p } = { prop: 'prop' }
>> { prop: 'prop' }

因此,这行代码意外地被解释为一个表达式语句.

So the line of code is interpreted as an expression statement, unexpectedly.

但是,如果我使用分号结尾运行相同的代码,则它将按预期运行.

But if I run the same code with a semi-colon at the end it runs as expected.

{ prop: p } = { prop: 'prop' };
>> Uncaught SyntaxError: Unexpected token =

这是可以预期的,因为除非我们用括号消除歧义,否则最初的{会告诉JavaScript引擎它是一个代码块.

This is expected since the initial { tells the JavaScript engine that it is a code block unless we disambiguate with parentheses.

为什么分号会出现这种情况,而没有分号会导致这种情况?

Why does this occur with the semi-colon but not without it?

推荐答案

Chrome使用非常简单的测试来查看行是否是对象文字:该行是否以{开头并以}结尾?如果是,则将该行评估为表达式.

Chrome uses a very simple test to see whether a line is an object literal or not: Does the line start with a { and end with a }? If yes, the line is evaluated as an expression.

{ prop: p } = { prop: 'prop' }通过了该测试,但{ prop: p } = { prop: 'prop' };没有通过.

{ prop: p } = { prop: 'prop' } passes that test, but { prop: p } = { prop: 'prop' }; does not.

有关更多信息(不同的输入,相同的原因),请参见对象文字比较的奇怪行为.

See Odd behaviour of comparison of object literals for more info (different input, same reason).

这篇关于为什么在使用分号时不将此JavaScript解释为代码块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-25 04:04