gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:30:46 24 4
gpt4 key购买 nike

我只是声明数据数组

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] = 2并且i变成3 。因此结果应为 {0, 1, 2, 3, 4}

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

最佳答案

摘自 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 的结果相匹配。

关于java - data[i++] = data[i++] * 2 结果令我惊讶,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20420273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com