运算符
首先我们要知道什么是表达式
例如 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,否则的话是表达式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>