JavaScript 赋值运算符用于将值赋给已声明的变量。等于号(=)是最常用的赋值运算符。例如:
var i = 10;
下表显示了所有的赋值运算符。
| 赋值运算符 | 示例 | 解释 |
|---|---|---|
| = | x = 15 | 将值 15 赋给 x |
| += | x += 15 | 这等同于 x = x + 15 |
| -= | x -= 15 | 这等同于 x = x – 15 |
| *= | x *= 15 | 这等同于 x = x * 15 |
| /= | x /= 15 | 这等同于 x = x / 15 |
| %= | x %= 15 | 这等同于 x = x % 15 |
JavaScript 赋值运算符示例
在此示例中,我们使用两个整数变量 a 和 Total,它们的值分别为 7 和 21。我们将使用这两个变量向您展示所有赋值运算符的工作功能。
<!DOCTYPE html>
<html>
<head>
<title> JavascriptAssignmentOperators</title>
</head>
<body>
<h1> AssignmentOperations </h1>
<script>
var a = 7, Total = 21;
document.write("Value of the Total = " + (Total += a) + "<br />");
document.write("Value of the Total = " + (Total -= a) + "<br />");
document.write("Value of the Total = " + (Total *= a) + "<br />");
document.write("Value of the Total = " + (Total /= a) + "<br />");
document.write("Value of the Total = " + (Total %= a) + "<br />");
</script>
</body>
</html>

在此赋值运算符程序中,我们声明了 2 个整数值 a 和 Total,并分别赋了值 7 和 21。下面的语句将对 a 和 Total 执行赋值操作,然后将输出写到相应的浏览器。
让我们看看 JS 赋值运算符的功能
document.write("Value of the Total = " + (Total += a) + "<br />");
Total += a 意味着
Total = Total + a = 21 + 7 = 28
document.write("Value of the Total = " + (Total -= a) + "<br />");
Total -= a 意味着
Total = Total – a = 28 – 7 = 21
document.write("Value of the Total = " + (Total *= a) + "<br />");
Total *= a 意味着
Total = Total * a = 21 * 7 = 147
document.write("Value of the Total = " + (Total /= a) + "<br />");
Total /= a 意味着
Total = Total / a = 147 / 7 = 21
document.write("Value of the Total = " + (Total %= a) + "<br />")
Total %= a 意味着
Total = Total + a = 21 % 7 = 0 (21/7 的余数为 0)
JavaScript 赋值运算符示例 2
在这个 JavaScript 示例中,我们使用两个整数变量 a 和 Total,它们的值分别为 7 和 21。我们将使用这些变量向您展示如何在段落中显示赋值运算符的输出。
<!DOCTYPE html>
<html>
<head>
<title> Example 2</title>
</head>
<body>
<h1> Assignment Operations </h1>
<p id = 'add'> Plus Equal to </p>
<p id = 'sub'> Subtraction Equal to </p>
<p id = 'mul'> Multiplication Equal to </p>
<p id = 'div'> Division Equal to </p>
<p id = 'mod'> Modulus Equal to </p>
<script>
var a = 3, Total = 12;
document.getElementById("add").innerHTML = "Value of the Total = " + (Total += a);
document.getElementById("sub").innerHTML = "Value of the Total = " + (Total -= a);
document.getElementById("mul").innerHTML = "Value of the Total = " + (Total *= a);
document.getElementById("div").innerHTML = "Value of the Total = " + (Total /= a);
document.getElementById("mod").innerHTML = "Value of the Total = " + (Total %= a);
</script>
</body>
</html>
Assignment Operations
Value of the Total = 15
Value of the Total = 12
Value of the Total = 36
Value of the Total = 12
Value of the Total = 0