18
a = 1;
b = "1";
if (a == b && a = 1) {
    console.log("a==b");
}

上面的 Javascript 代码会导致ifGoogle Chrome 26.0.1410.43中的语句出现错误:

未捕获的 ReferenceError:分配中的左侧无效

a我认为这是因为语句第二部分中的&&变量无法a=1赋值。但是,当我尝试下面的代码时,我完全糊涂了!

a = 1;
b = "1";
if (a = 1 && a == b) {
    console.log("a==b");
}

为什么一种说法正确,另一种说法错误?

4

4 回答 4

60

= has lower operator precendence than both && and ==, which means that your first assignment turns into

if ((a == b && a) = 1) {

Since you can't assign to an expression in this way, this will give you an error.

于 2013-05-18T07:20:01.110 回答
21

The second version is parsed as a = (1 && a == b); that is, the result of the expression 1 && a == b is assigned to a.

The first version does not work because the lefthand side of the assignment is not parsed as you expected. It parses the expression as if you're trying to assign a value to everything on the righthand side--(a == b && a) = 1.

This is all based on the precedence of the various operators. The problem here stems from the fact that = has a lower precedence than the other operators.

于 2013-05-18T07:17:23.170 回答
6

Because the order of operations is not what you expect. a == b && a = 1 is equivalent to (a == b && a) = 1 which is equivalent to false = 1.

If you really want to do the assignment, you need to use parentheses around it: a == b && (a = 1).

于 2013-05-18T07:19:11.557 回答
2

In if (a = 1 && a == b),

The operations to be first performed is 1 && a == b. 1 && the result of a == b is performed. The result of this && operation is assigned to a.

于 2013-05-18T07:21:29.177 回答