let a = 70;
a++; // This returns the value before incrementing.
console.log(a) // returns 71
谁能给我解释一下为什么这个不返回70 ?
let b = 70;
++b; // Using it as a prefix returns the value after incrementing.
console.log(b) // returns 71
我知道前缀是怎么工作的。
我已经阅读了关于这个主题的解释并观看了视频,但它仍然让我感到困惑。谢谢你。
这两个版本都增加了它们所应用的值。如果你不改变增量表达式本身的值,它们是等价的,它们都和i += 1
做同样的事情。只有在使用递增表达式的结果时才需要注意:
let a = 70;
console.log(a++); // outputs 70, the old value of a, but a will be 71 afterwards
console.log(a) // outputs 71; no matter how you increment, after the increment, the value has changed
let b = 70;
console.log(++b); // outputs 71; the new value of b is produced
console.log(b) // outputs 71; same as in case a
您要注意的差异只有在内联使用这些前缀/后缀操作符时才能看到,就像这样:
let a = 5;
console.log(a++);
let b = 5;
console.log(++b);
return"不是正确的术语(函数返回,表达式不返回)。
a++
对作为递增前的值。
你不是在看表达式计算的值,你只是在看变量的值。
let a = 70;
let result_of_a_plus_plus = a++; // This evaluates as the value before incrementing.
let b = 70;
let result_of_plus_plus_b = ++b; // Using it as a prefix increments the value before the expression is evaluated.
console.log({
a,
result_of_a_plus_plus,
b,
result_of_plus_plus_b
});