Javascript和自动分号插入 [英] Javascript and automatic semicolon insertion
问题描述
var x=0, y=0;
var z=
x
++
++
y
注释说:
因为Postfix递增/递减运算符(I / DO)和操作数之间的LineTerminator(LT)不允许,自动分号插入后由[LT]分隔的两个引用之间的两个IO(就像两个DO及其组合)导致语法错误
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
为什么此代码会导致语法错误?我认为这是一个有效的代码片段。上面的代码等于 var z = x; ++ ++ y;
。表达式 ++ ++ y
是nofollow>。那么问题是什么?
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;
. Expression ++ ++ y
is allowed by javascript grammar. So what's the problem?
推荐答案
此代码将变为:
var z = x;
++ ++ y;
++ ++ y
是问题的根源。让我们来看看为什么......
The ++ ++ y
is the root of the problem. Let’s look at why...
++ ++ y
评估为 + +(++ y)的
。第一步是评估(++ y)
。 ++
运算符递增它旁边的变量引用的值,并返回递增的值。这里的重要部分是它不返回引用,只返回值。所以第二步是 ++(1)
,(或其他 ++ y
产生的),这是一个错误,因为只有引用可以递增。
++ ++ y
gets evaluated as ++(++y)
. The first step is to evaluate (++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.
这篇关于Javascript和自动分号插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!