運算子
#首先我們要知道什麼是表達式
例如i++ ; a+b 這都是表達式
一元運算子:只能操作一個值得運算子、叫做一元運算子
遞增 ++ 與遞減- -
看如下程式碼:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>运算符</title> </head> <script type="text/javascript"> var box=100; box++; //box--; //++box; //--box; document.write(box); </script> <body> </body> </html>
前置遞增,輸出101 後置遞增輸出101
前置遞減,輸出99 後置遞減輸出99
註:前置和後置的差異
var box=100;
//age = ++box; //先把box 累加到101,然後賦值給age
//= box ++; //先將box 賦值給age ,age=100,然後累加
//age = --box //先將box 累減到99,然後賦值給age
//= box -- //先將box值賦值給age age=100,然後去減
#+ -運算子var box=100;
+box; //正數-box //負數加號(+)有個自動轉型的功能
如下程式碼所示<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>一元运算符</title>
</head>
<script type="text/javascript">
var box="89";
alert(typeof +box); //如果没有加号,是string类型,有加号则是number类型
</script>
<body>
</body>
</html>
算術運算子
加上(+)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>算术运算符</title>
</head>
<script type="text/javascript">
var a = 10;
var b = 15;
var c = a+b;
document.write(c);
</script>
<body>
</body>
</html>
#減去(-)
##
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>算术运算符</title> </head> <script type="text/javascript"> var a = 10; var b = 15; var c = a-b; document.write(c); </script> <body> </body> </html>
乘(*)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>算术运算符</title> </head> <script type="text/javascript"> var a = 10; var b = 15; var c = a*b; document.write(c); </script> <body> </body> </html>
(/)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>算术运算符</title> </head> <script type="text/javascript"> var a = 15; var b = 15; var c = a/b; document.write(c); </script> <body> </body> </html>
################################### #餘(%)#########
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>算术运算符</title> </head> <script type="text/javascript"> var a = 15; var b = 5; var c = a%b; document.write(c); </script> <body> </body> </html>#########賦值運算子#####################賦值運算符的嵌套使用:如下案例###
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>赋值运算符</title> </head> <script type="text/javascript"> y = ( x = 2) + 5; alert(x); alert(y); </script> <body> </body> </html>#########比較運算子########################## #########################三元運算子############語法: 表達式1 ? 表達式2 : 表達式3 #########實例:######
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>三元运算符</title> </head> <script type="text/javascript"> var x = 5; y = (x=5)?x:1; document.write(y); </script> <body> </body> </html>###註:如果表達式1成立,則輸出的結果是表達式2,否則的話是表達式2,否則的話是表達式3;如上述案例x=5;進行判斷表達式1是否成立,成立輸出x的值,不成立輸出1 彈出值為5;############邏輯運算子#### ##############
&&(条件必须同时满足,才为真)
x=2;y=6;
x&&y>6 ;
此时x和y只有一项满足大于6 所以结果为false;
||(条件只要满足其中一个即为真)
x=2;y=6;
x||y>6 ;
此时x和y其中是有一项满足条件的,所以结果为true;
!(取逻辑值得反面,如果为真就取假,为假就取真)
x=5;y=8;
!(x>y);
首先先判断x是否大于y ,的、不大于,即为假,非假即为真,所以结果为true
字符串链接符 +
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>字符串连接符</title> <script type="text/javascript"> var a = "中国,"; var b = "你好"; var c = a + b; document.write(c); </script> </head> <body> </body> </html>