Why doesn't the shorthand arithmetic operator ++ after the variable name return 2 in the following statement?

前端 未结 3 1094
-上瘾入骨i
-上瘾入骨i 2020-11-27 22:10

I have a very simple arithmetic operator but am at my wits end why it doesn\'t return 2. The code below returns 1. I thought that x++ equates to x = x + 1;

C

3条回答
  •  攒了一身酷
    2020-11-27 22:42

    I think of x++ and ++x (informally) as this:

    x++:

    function post_increment(x) {
      return x; // Pretend this return statement doesn't exit the function
      x = x + 1;
    }
    

    ++x:

    function pre_increment(x) {
      x = x + 1;
      return x;
    }
    

    The two operations do the same thing, but they return different values:

    var x = 1;
    var y = 1;
    
    x++; // This returned 1
    ++y; // This returned 2
    
    console.log(x == y); // true because both were incremented in the end
    

提交回复
热议问题