简体   繁体   English

语法错误,还是没有语法错误?

[英]Syntax error, or no syntax error?

var zero = 0;
zero.toString();   // '0' --> fine
0.toString();      // syntax error!
0..toString();     // '0' --> fine

My conclusion: calling x.toString() doesn't only depend on the value of x , but also on the way x is presented . 我的结论是:调用x.toString()不仅取决于x的值,而且取决于x表示方式

Are there other such examples in JavaScript where I might get an unexpected syntax error due to presentation? JavaScript中是否还有其他此类示例,由于演示,我可能会收到意外的语法错误?

Well, there are other cases where the context of where symbols appear affects how they behave, for example, statement Block's vs Object Literals: 好吧,在其他情况 ,符号出现的上下文会影响符号的行为,例如语句Block的vs Object Literals:

{}          // empty block
var o = {}; // empty object
({});       // empty object
0,{}        // empty object

{ foo: 'bar'} // block, `foo` label, 'bar' ExpressionStatement
var o = { foo: 'bar'}; // object literal, declaring a `foo` property
                       // whose value is 'bar'

They look exactly the same, but blocks are evaluates in "statement context", object literals are evaluated in expression context . 它们看起来完全一样,但是块在“语句上下文”中求值,对象文字在表达式上下文中求值。

Also, Function Declarations vs. Function Statements, eg: 同样,函数声明与函数声明,例如:

function foo() {}.length;   // SyntaxError, `foo` is a function declaration
0,function foo() {}.length; // 0, `foo` is a function expression
(function foo {}).length;   // 0

The example you post, relates to the way the grammar of Numeric literals are defined, the decimal part after the dot is actually optional, for example: 您发布的示例与数字文字语法的定义方式有关,点后的小数部分实际上是可选的,例如:

var n = 0.;

Is a valid Numeric literal, that's why, accessing 0.toString gives you a SyntaxError , the interpreter would expect the decimal part, instead the s character. 是一个有效的数字文字,这就是为什么访问0.toString会给您一个SyntaxError ,解释器期望小数部分,而不是s字符。

See also: 也可以看看:

The value of a variable doesn't matter, but the way it is "presented" might make it valid or invalid syntax. 变量的值无关紧要,但是“表示”变量的方式可能会使它成为有效或无效的语法。 See this highly upvoted answer . 看到这个高度评价的答案 It's just an oddity of the EcmaScript syntax definition. 这只是EcmaScript语法定义的怪异之处。

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

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