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

后端 未结 4 1463
太阳男子
太阳男子 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:15

    The i-- will be evaluated only after the loop condition is evaluated but before the statements within the loop. This is the decrement postfix operator. That means that initially the evaluation of the condition in the loop condition would be true. This will fire the execution of the statements in the loop's body. When the statements in the loop's body will be executed, since the i had be decremented by one, it would be equal to 0. Hence the evaluation of the loop condition would be false and the statements in the loop's body will not be executed again.

    0 讨论(0)
  • 2021-01-29 05:19

    i-- is not the same as i=i-1, when used in a loop.

    i-- will be evaluated after the condition, but before the loop contents are run, whereas i=i-1 will be evaluated before the condition, so will evaluate to false.

    I guess in that respect --i is more similar to i=i-1, as it is also evaluated prior to the condition.

    You can think of

    while (i--) {...}
    

    As being equivalent to

    while (i = i - 1, i + 1) {...}
    
    0 讨论(0)
  • 2021-01-29 05:26

    You should use --ias the pre-decrement operator.

    See the docs here

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题