Why is JavaScript's post-increment operator different from C and Perl?

后端 未结 4 639
盖世英雄少女心
盖世英雄少女心 2021-01-05 17:39

I\'m studying for an exam on JavaScript at the moment. I\'ve also got a little knowledge of C and Perl so I\'m familiar with prefix and postfix operators in all three langua

4条回答
  •  天命终不由人
    2021-01-05 18:24

    In C, the line

    x += x--;
    

    is undefined behaviour. It seems like your particular compiler is treating it like:

    oldx = x--;
    x = x + oldx
    

    However, the ECMAScript specification does specify op= - and it gets the value of the left-hand-side before evaluating the right-hand-side.

    So it would be equivalent to:

    oldx = x--;
    x = oldx + oldx
    

提交回复
热议问题