[英]Javascript and automatic semicolon insertion
test262 test suite has test containing source: test262测试套件包含包含以下内容的测试 :
var x=0, y=0;
var z=
x
++
++
y
The annotation says: 注释说:
Since LineTerminator(LT) between Postfix Increment/Decrement Operator(I/DO) and operand is not allowed, two IO(just as two DO and their combination) between two references separated by [LT] after automatic semicolon insertion lead to syntax error 由于不允许在后缀增减运算符(I / DO)和操作数之间使用LineTerminator(LT),因此,在自动分号插入后,两个由[LT]分隔的引用之间的两个IO(正好是两个DO及其组合)会导致语法错误
Why does this code lead to syntax error? 为什么此代码会导致语法错误? I think it's a valid code snippet. 我认为这是有效的代码段。 The code above equals to var z=x; ++ ++ y;
上面的代码等于var z=x; ++ ++ y;
var z=x; ++ ++ y;
. 。 Expression ++ ++ y
is allowed by javascript grammar. JavaScript语法允许使用表达式++ ++ y
。 So what's the problem? 所以有什么问题?
This code will become: 该代码将变为:
var z = x;
++ ++ y;
The ++ ++ y
is the root of the problem. ++ ++ y
是问题的根源。 Let's look at why... 让我们看看为什么...
++ ++ y
gets evaluated as ++(++y)
. ++ ++ y
被评估为++(++y)
。 The first step is to evaluate (++y)
. 第一步是评估(++y)
。 The ++
operator increments the value referenced by the variable it is next to, and returns the incremented value. ++
运算符递增其旁边的变量引用的值,然后返回递增的值。 The important part here is that it does not return a reference, just a value . 这里的重要部分是它不返回引用,而只是返回值 。 So the second step would be ++(1)
, (or whatever ++y
yielded), which is an error, since only references can be incremented. 因此,第二步将是++(1)
,(或产生的++y
),这是一个错误,因为只能增加引用。
That evaluates to: 评估结果为:
var x = 0, y = 0;
var z = x ++ ++ y; //MAKES NO SENSE!
The grammar does not allow a new-line to precede a ++
or --
operator; 语法不允许换行符位于++
或--
运算符之前; such a new-line must be converted to a ;
这样的换行符必须转换为;
. 。 Consequently, the expression must be parsed as though it had been: 因此,必须像以前那样对表达式进行解析:
var x = 0 , y = 0 ;
var z = x ;
++ ;
++ y ;
The third line is illegal. 第三行是非法的。
References: 参考文献:
Section 7.9.1, "Rules of Automatic Semicolon Insertion", rule 3 第7.9.1节“自动分号插入规则”,规则3
Section 11.3, "11.3 Postfix Expressions". 第11.3节“ 11.3后缀表达式”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.