理解前缀和后缀递增/递减
在这一步中,你将学习 JavaScript 中前缀和后缀递增/递减运算符的区别。这些运算符看起来相似,但在表达式中使用时行为不同。
打开 arithmetic.html
文件,并使用以下代码更新 <script>
部分:
<script>
// Postfix Increment (x++)
let a = 5;
let b = a++;
console.log("Postfix Increment:");
console.log("a =", a); // a is incremented after the value is assigned
console.log("b =", b); // b gets the original value of a
// Prefix Increment (++x)
let x = 5;
let y = ++x;
console.log("\nPrefix Increment:");
console.log("x =", x); // x is incremented before the value is assigned
console.log("y =", y); // y gets the incremented value of x
// Similar concept applies to decrement operators
let p = 10;
let q = p--;
console.log("\nPostfix Decrement:");
console.log("p =", p); // p is decremented after the value is assigned
console.log("q =", q); // q gets the original value of p
let m = 10;
let n = --m;
console.log("\nPrefix Decrement:");
console.log("m =", m); // m is decremented before the value is assigned
console.log("n =", n); // n gets the decremented value of m
</script>
当你在浏览器中打开此 HTML 文件并检查开发者控制台时,你将看到以下示例输出:
Postfix Increment:
a = 6
b = 5
Prefix Increment:
x = 6
y = 6
Postfix Decrement:
p = 9
q = 10
Prefix Decrement:
m = 9
n = 9
需要理解的关键点:
- 后缀
x++
:返回原始值,然后递增
- 前缀
++x
:先递增,然后返回新值
- 同样的原则适用于递减运算符
x--
和 --x
- 当运算符用于表达式或赋值时,这种区别很重要