search

Home  >  Q&A  >  body text

javascript - An assignment operation problem

var a=0;
b=(a=3) (a=4);
alert(a);
alert(b);
Result a=4,b= 7

I would like to ask, why is a 4? Is the assignment operation from right to left?

phpcn_u1582phpcn_u15822702 days ago834

reply all(5)I'll reply

  • 仅有的幸福

    仅有的幸福2017-06-26 10:57:04

    Order of operations:

    var a = 0; // a 0
    b = (a = 3) + (a = 4);
    // a = 3 ----> a为3,整个赋值语句返回3
    // a = 4 ----> a为4,整个赋值语句返回4
    // 由于返回值的内存和赋值操作用到的a的内存不同,所以b的运算所用的值,只和返回值有关,不受a的值变化的影响,因此,b = 3 + 4 = 7
    // 所以,最终a为4,b为7

    reply
    0
  • 怪我咯

    怪我咯2017-06-26 10:57:04

    Assignment operations are combined from right to left. So the first thing is to assign (a=3)+(a=4) to b. However, (a=3)+(a=4) is executed from left to right. So it shows that 3 is assigned to a, and then 4 is assigned to a. So a ends up being 4 and b ends up being 7.

    reply
    0
  • 世界只因有你

    世界只因有你2017-06-26 10:57:04

    First execute a=3, then execute a=4, so in the end a is 4

    reply
    0
  • 黄舟

    黄舟2017-06-26 10:57:04

    a is assigned the value 4

    reply
    0
  • PHP中文网

    PHP中文网2017-06-26 10:57:04

    b=(a=3)+(a=4) This line of code is executed from left to right. When a=3 is executed, 3 is assigned to a. When a=4, 4 is assigned to a. The final value of a is 4.

    reply
    0
  • Cancelreply