在本教程中,您将学习如何使用 JavaScript 赋值运算符为变量赋值。
JavaScript 赋值运算符简介
赋值运算符 =
为变量赋值。赋值运算符的语法形式是 let a = b;
。在此语法中,JavaScript 首先计算表达式 b
并将结果分配给变量 a
。
以下示例声明 counter
变量并将其值初始化为零:
let counter = 0;
以下示例将 counter
变量加一并将结果分配给counter
变量:
let counter = 0;
counter = counter + 1;
在评估第二条语句时,JavaScript 首先评估右侧的表达式 counter + 1
并将结果分配给 counter
变量。第二次赋值后,counter
变量为 1
。
为了使代码更简洁,您可以像这样使用运算符 +=
:
let counter = 0;
counter += 1;
在此语法中,您不必在赋值中重复编写变量 counter
两次。
下表说明了赋值运算符,它们是另一个运算符和赋值的简写:
Operator | Meaning | Description |
---|---|---|
a = b | a = b | Assigns the value of b to a . |
a += b | a = a + b | Assigns the result of a plus b to a . |
a -= b | a = a - b | Assigns the result of a minus b to a . |
a *= b | a = a * b | Assigns the result of a times b to a . |
a /= b | a = a / b | Assigns the result of a divided by b to a . |
a %= b | a = a % b | Assigns the result of a modulo b to a . |
a &=b | a = a & b | Assigns the result of a AND b to a . |
a |=b | a = a | b | Assigns the result of a OR b to a . |
a ^=b | a = a ^ b | Assigns the result of a XOR b to a . |
a <<= b | a = a << b | Assigns the result of a shifted left by b to a . |
a >>= b | a = a >> b | Assigns the result of a shifted right (sign preserved) by b to a . |
a >>>= b | a = a >>> b | Assigns the result of a shifted right by b to a . |
链接 JavaScript 赋值运算符
如果要将单个值分配给多个变量,可以链接赋值运算符。例如:
let a = 10, b = 20, c = 30;
a = b = c; // 所有变量都是30
在此示例中,JavaScript 从左到右计算。因此,它执行以下操作:
let a = 10, b = 20, c = 30;
b = c; // b 是 30
a = b; // a 也是 30
结论
- 使用赋值运算符
=
为变量赋值。 - 如果要将单个值分配给多个变量,请链接赋值运算符。