有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java数据[i++]=data[i++]*2结果令我惊讶

我只是声明数据数组

data = {0, 1, 2, 3, 4},  i = 1;  
data[i++] = data[i++] * 2;

我用Java和Javascript进行测试,结果都是

{0, 4, 2, 3, 4}

一开始我觉得这对我来说太奇怪了

data[i++] * 2, data[1] * 2 = 2,

然后i变成2,然后data[2] = 2i变成3。所以结果应该是{0, 1, 2, 3, 4}

有人知道这个结果的原因吗


共 (6) 个答案

  1. # 1 楼答案

    这很简单。。。(增加后就可以了)

    右手侧的i++值更改为2,因为左手侧的后增量

    data[i++]=data[i++]*2
    

    其扩展如下:

    data[1]=data[2]*2
    data[1]=2*2;
    

    因此

    data=[0,4,2,3,4]
    
  2. # 2 楼答案

    Javascript

    data[i++] = data[i++] * 2; // i === 1
    data[1] = data[i++] * 2; // i === 2
    data[1] = data[2]*2; // i === 3
    

    ++运算符递增变量,然后返回(计算)原始值

    一个简单的例子是:

    var x = 0;
    console.log(x + (x++) + x) // 1
    

    第一个和第二个x的值为0,而第三个x的值为1(因为它已递增)

  3. # 3 楼答案

    在Java中,a[x] = y;形式的赋值是evaluated left-to-right。也就是说,xy之前进行求值。这个same is true for JavaScript

    此外,在使用is之后,增量后运算符x++会更改x的值

    将这两个事实与视觉解释结合起来(见下文),这一切都应该是有意义的:

    i = 1;
    
    data[i++] = data[i++] * 2;
         ^           ^
         |           |
         1           2
    
    System.out.println(i); // would display '3'
    
  4. # 4 楼答案

    希望它有意义

    data[i++] = data[i++] * 2;
    

    第一步:

     data[i++] -> data[1]//because i is under post increment
    

    第二步:

     data[i++] * 2->data[2]*2-> 2*2 ->4 // now i is 2 
    

    第三步:

    data[1] = 4;//interpreter interprets  left to right
    
  5. # 5 楼答案

    来自Java语言规范http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.1

    If the left-hand operand is an array access expression (§15.13), possibly enclosed in one or more pairs of parentheses, then:

    • First, the array reference subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index subexpression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs.

    • Otherwise, the index subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and the right-hand operand is not evaluated and no assignment occurs.

    • Otherwise, the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

    换句话说,左侧的数组索引必须在右侧之前求值,以符合Java语言规范

    这意味着您将分配到data[1],分配的值将是data[2] * 2

    但是,如果你问的是Javascript,我只能建议Javascript的制造商希望让结果与Java的结果相匹配

  6. # 6 楼答案

    它是一个自动递增后递增(即使用变量的当前值,但使用后,其值会自动递增,以便下次使用)

    在第一个data[i++]中,它使用i的值(即1),然后将其增加,因此在第二个data[i++]中,i是2

    因此方程变成data[1]=data[2]*2