Why code:

var data=[1,2,3]; var i=0; alert(data[i++]*=2); 

Differs from:

 var data2=[1,2,3]; var b=0; alert(data2[b++]=data2[b++]*2); 
  • one
    Probably because data [i ++] * = 2 is equivalent to data [i] = data [i ++] * 2 and not data [i ++] = data [i ++] * 2 - ReinRaus

1 answer 1

In the first case, the following occurs at index 0, the element is taken, multiplied by two and written there. Therefore, the result will be [2,2,3] and output 2. After the operation i = 1 .

In the second case, the element will be taken at index 0, multiplied by 2, then b will become equal to 1. And only after this will assignment to the element with index 1. We get [2,2,3] . and b becomes 2 (one more increment will occur).

In general, such constructions are very discouraged ( a[i++] = a[i++] * 2 ), since the result is sometimes very unpredictable. In the case of C ++, the result may be completely different depending on the compiler's mood.

  • thanks, but in the case of javascript 2 and 4 - Undefined
  • Only the mood of the computer has nothing to do with it, everything depends strictly on the compiler - Crasher
  • Since assignment is not a sequence point, two increments give undefined behavior (in C ++) - VladD
  • one
    @Crasher - and no one spoke about the mood of the computer :) @ maxim-yurewitch and I derived 2 and 2. Apparently, in the case of JavaScript, different browsers (using different versions of JavaScript can be interpreted differently). For example, your alert could just output the left side of the expression. And at that time, the value of i and / or b could already have changed. And I could just remember the result. @VladD thanks, KO! - KoVadim
  • IE6 apparently used, but I already figured out. Post increment first assigns a value, and then increments, but in the first expression, because of the expression with the operation, the index is calculated 1 time. Data [0] = data [0] * 2 = 1 * 2 = 2; In the second post, the increment first assigns a value, and then increments, and then it increments the increased value, and increments. Data [0] = data [1] * 2 = 2 * 2 = 4; - Undefined