++ 增量
x = ++y // When y = 6 x = 6
x = y++ // And y = 6 x = 5
-- 递减
x = --y // When y = 4 x = 4
x = y-- // When y = 4 x = 5
有人可以澄清一下吗? 谢谢。
最佳答案
唯一有点棘手的情况是:
x = --y // When y = 4 x = 4
你一定是在看 y
afterward。如果您查看 y
,您会看到 5
。
前缀自减(--y
)和后缀自减(y--
)的基本规则是:
无论哪种方式,操作数(在本例中为
y
)都会减 1。唯一的区别是该表达式的结果(--y
或y--
) 是。如果运算符出现在操作数之前 (
--y
) 它是一个“前缀”递减:递减发生在之前表达式的结果被采用。所以结果就是y
递减后的值。如果运算符出现在操作数 (
y--
) 之后,则它是一个“后缀”递减:递减发生在之后表达式的结果被采用。所以结果是递减前的值。
例子:
var x, y;
y = 5;
snippet.log("Before prefix decrement: y = " + y);
x = --y; // Result is the value **after** the decrement
snippet.log("After prefix decrement: x = " + x + ", y = " + y);
y = 5;
snippet.log("Before postfix decrement: y = " + y);
x = y--; // Result is the value **before** the decrement
snippet.log("After postfix decrement: x = " + x + ", y = " + y);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
关于javascript - JavaScript In-/Decrement 背后的逻辑是什么?有人可以澄清这一点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30201915/