i— and i = i-1 not evaluating the same

后端 未结 4 1467
太阳男子
太阳男子 2021-01-29 04:48

I thought that i-- is a shorthand for i = i - 1, but I discovered that both evaluate different:

         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-29 05:30

    When you do i--, the value of i is used and then decremented. But in case of a prefix --1 operator it is different, as in, it will be decremented and then used.

    var i = j = 1;
    console.log(i--); // still 1
    console.log(i); // now 0
    console.log(--j) // 0
    console.log(j); // again 0
    

    Why explain the above?

    To show you what's going on actually behind when you use pre-fix and post-fix operators, though it is not mainly concerned with the question, but I thought it would be better to know.

    Now the actual answer

    What i = i - 1 does is it evaluates as soon as the code is encountered, so i is actually 0, you can say it acts similar to pre-fix decrement operator, in this case, but i-- is still 1 when the condition used in while is evaluated for the first time and then when the second time the while condition is checked, it is 0, which is falsey and hence the loop ends.

提交回复
热议问题