JavaScript 赋值

JavaScript 将某一数值赋给某个变量的过程,称为赋值。


JavaScript 赋值运算符

赋值运算符向 JavaScript 变量赋值。

运算符例子等同于
=x = yx = y
+=x += yx = x + y
-=x -= yx = x - y
*=x *= yx = x * y
/=x /= yx = x / y
%=x %= yx = x % y
<<=x <<= yx = x << y
>>=x >>= yx = x >> y
>>>=x >>>= yx = x >>> y
&=x &= yx = x & y
^=x ^= yx = x ^ y
|=x |= yx = x | y
**=x **= yx = x ** y

赋值实例

= 赋值运算符向变量赋值。

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <h1>= 运算符</h1>
  5. <p id="demo">
  6. <script>
  7. var x = 7;
  8. document.getElementById("demo").innerHTML = x;
  9. </script>
  10. </body>
  11. </html>

+= 赋值运算符向变量添加值。

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <h1>+= 运算符</h1>
  5. <p id="demo">
  6. <script>
  7. var x = 7;
  8. x += 8;
  9. document.getElementById("demo").innerHTML = x;
  10. </script>
  11. </body>
  12. </html>

-= 赋值运算符从变量中减去一个值。

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <h1>-= 运算符</h1>
  5. <p id="demo">
  6. <script>
  7. var x = 7;
  8. x -= 8;
  9. document.getElementById("demo").innerHTML = x;
  10. </script>
  11. </body>
  12. </html>

*= 赋值运算符相乘变量。

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <h1>*= 运算符</h1>
  5. <p id="demo">
  6. <script>
  7. var x = 7;
  8. x *= 8;
  9. document.getElementById("demo").innerHTML = x;
  10. </script>
  11. </body>
  12. </html>

/= 赋值运算符对变量相除。

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <h1>/= 运算符</h1>
  5. <p id="demo">
  6. <script>
  7. var x = 7;
  8. x /= 8;
  9. document.getElementById("demo").innerHTML = x;
  10. </script>
  11. </body>
  12. </html>

%= 赋值运算符把余数赋值给变量。

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <h1>%= 运算符</h1>
  5. <p id="demo">
  6. <script>
  7. var x = 7;
  8. x %= 8;
  9. document.getElementById("demo").innerHTML = x;
  10. </script>
  11. </body>
  12. </html>