Addition assignment += behavior in expression

前端 未结 3 2078
你的背包
你的背包 2021-01-30 20:11

Recently I came across this question: Assignment operator chain understanding.

While answering this question I started doubting my own understanding of the behavior of t

3条回答
  •  花落未央
    2021-01-30 20:33

    It just uses a variation of order of ops.

    If you need a reminder of order of ops:

    PEMDAS:

    P = Parenthesis

    E = Exponents

    MD = Multiplication/Division

    AS = Addition/Subtraction

    The rest left to right.

    This variation just is read left to right, but if you see a parenthesis do everything inside it, and replace it with a constant then move on.

    First ex:

    var b = (a+=(a+=a))

    var b = (1+=(1+=1))

    var b = (1+=2)

    var b = 3

    Second ex:

    var b = (a+=a)+(a+=a)

    var b = (1+=1)+(a+=a)

    var b = 2 + (2+=2)

    var b = 2 + 4

    var b = 6

    var a = 1
    var b = (a += (a += a))
    console.log(b);
    
    a = 1
    b = (a += a) + (a += a)
    console.log(b);
    
    a = 1
    b = a += a += a;
    console.log(b);

    The last one b = a += a += a since there are no parenthesis, it automatically becomes b = 1 += 1 += 1 which is b = 3

提交回复
热议问题