JavaScript 运算符
更新时间:2022-04-24 09:38JavaScript 运算符
我们先来个简单实例,指定变量值,并将值相加:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>95知识库(995w.com)</title> </head> <body> <p>点击按钮计算 x 的值.</p> <button onclick="myFunction()">点击这里</button> <p id="demo"></p> <script> function myFunction() { y=5; z=2; x=y+z; document.getElementById("demo").innerHTML=x; } </script> </body> </html>
JavaScript 算术运算符
y=5,下面的表格解释了这些算术运算符:
运算符 | 描述 | 例子 | x 运算结果 | y 运算结果 |
---|---|---|---|---|
+ | 加法 | x=y+2 | 7 | 5 |
- | 减法 | x=y-2 | 3 | 5 |
* | 乘法 | x=y*2 | 10 | 5 |
/ | 除法 | x=y/2 | 2.5 | 5 |
% | 取模(余数) | x=y%2 | 1 | 5 |
++ | 自增 | x=++y | 6 | 6 |
x=y++ | 5 | 6 | ||
-- | 自减 | x=--y | 4 | 4 |
x=y-- | 5 | 4 |
JavaScript 赋值运算符
赋值运算符用于给 JavaScript 变量赋值。给定 x=10 和 y=5,下面的表格解释了赋值运算符:
运算符 | 例子 | 等同于 | 运算结果 |
---|---|---|---|
= | x=y | x=5 | |
+= | x+=y | x=x+y | x=15 |
-= | x-=y | x=x-y | x=5 |
*= | x*=y | x=x*y | x=50 |
/= | x/=y | x=x/y | x=2 |
%= | x%=y | x=x%y | x=0 |
用于字符串的 + 运算符
+ 运算符用于把文本值或字符串变量加起来(连接起来)。如需把两个或多个字符串变量连接起来,请使用 + 运算符。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>95知识库(995w.com)</title> </head> <body> <p>点击按钮创建及增加字符串变量。</p> <button onclick="myFunction()">点击这里</button> <p id="demo"></p> <script> function myFunction() { //要想在两个字符串之间增加空格,需要把空格插入一个字符串之中 //如 txt1="What a very "; txt1="What a very"; txt2="nice day"; txt3=txt1+txt2; document.getElementById("demo").innerHTML=txt3; } </script> </body> </html>
对字符串和数字进行加法运算
两个数字相加,返回数字相加的和,如果数字与字符串相加,返回字符串,如下实例:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>95知识库(995w.com)</title> </head> <body> <p>点击按钮创建及增加字符串变量。</p> <button onclick="myFunction()">点击这里</button> <p id="demo"></p> <script> function myFunction() { var x=5+5; var y="5"+5; var z="Hello"+5; var demoP=document.getElementById("demo"); demoP.innerHTML=x + "<br>" + y + "<br>" + z; } </script> </body> </html>