具有操作符优先级的JavaScript奇怪行为!!!! 1

时间:2018-11-14 10:20:37

标签: javascript operators operator-precedence

您认为此表达的结果是什么?

var a = 10;
a = a + (a = 5);
console.log(a);

// a = 10?

不! 15岁!

现在让我们看看其他类似的语句:

var a = 10;
    a = (a = 5) + a;
    console.log(a);
    
    // a = 15? 

还是不,现在是10。为什么呢?我听不懂但是等等,还有两个:

var a = 10;
a = a + a++;
console.log(a);

// a = 21? Haha no! Its 20!

最后一个:

var a = 10;
a = a++ + a;
console.log(a);

// 21))) now my mind is blown away (

所以有人能说出为什么javascript这样表现吗?

2 个答案:

答案 0 :(得分:1)

为了更好地理解这一点,让我们考虑另一个变量

案例1

var a = 10;
a = a + (a = 5); 
console.log(a); // 15

a = 10;
var b = a + (a = 5);
console.log(a); // 5
console.log(b); // 15

a + (a = 5)
5 + (a = 5) // here a is assigned a value 5 and bracket returns 5
5 + 5 // here value of a is 5
10 // value will be assigned to variable on LHS

案例2

var a = 10;
a = (a = 5) + a;
console.log(a); // 10


a = 10;
var b = (a = 5) + a;
console.log(a); // 5
console.log(b); // 10

(a = 5) + a
(a = 5) + a // here a is assigned a value 5 and bracket returns value 5
5 + 5 // here value of a is 5
10 // value will be assigned to variable on LHS

案例3

var a = 10;
a = a + a++;
console.log(a); // 20

a = 10;
var b = a + a++;
console.log(a); // 11
console.log(b); // 20

a + a++ // post increment i.e. it will return the value first and then increment
10 + 10 // where value of a will 10 + 1 i.e. 11 
20 // value will be assigned to variable on LHS

案例4

var a = 10;
a = a++ + a;
console.log(a); // 21

a = 10;
var b = a++ + a;
console.log(a); // 11
console.log(b); // 21

a++ + a // post increment i.e. it will return the value first and then increment
10 + a // where value of a will 10 + 1 i.e. 11
10 + 11 // as value of a is 11
21 // value will be assigned to variable on LHS

答案 1 :(得分:0)

var a = 10;
a = a + (a = 5);
console.log(a);

// a = 10?

之所以为15,是因为 a 的值为10,然后您添加了(a = 5),这将 a 的值更改为5.因此,您做了10 + 5。

var a = 10;
    a = (a = 5) + a;
    console.log(a);
    
    // a = 15? 

现在,您首先具有(a = 5),然后在添加 a 之前将其值更改为5。因此,您要做的是5 + 5。

希望这会有所帮助。