JavaScript 运算符
运算符 = 用于赋值。
运算符 + 用于加值。
运算符 = 用于给 JavaScript 变量赋值。
算术运算符 + 用于把值加起来。
实例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</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+2 | x=7 |
| - | 减 | x=y-2 | x=3 |
| * | 乘 | x=y*2 | x=10 |
| / | 除 | x=y/2 | x=2.5 |
| % | 求余数 (保留整数) | x=y%2 | x=1 |
| ++ | 累加 | x=++y | x=6 |
| -- | 递减 | x=--y | x=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>php中文网(php.cn)</title>
</head>
<body>
<p>点击按钮创建及增加字符串变量。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction()
{
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>php中文网(php.cn)</title>
</head>
<body>
<p>点击按钮创建及增加字符串变量。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction()
{
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>php中文网(php.cn)</title>
</head>
<body>
<p>点击按钮创建及增加字符串变量。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction()
{
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>php中文网(php.cn)</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>规则:如果把数字与字符串相加,结果将成为字符串!
运行程序尝试一下

我又来了
明白,真心好
8年前 添加回复 0