Js运算符
来自CloudWiki
目录
一元运算符
++ -- + - !
<script> var a=0; ++a; a++; --a; a--; !true </script>
算术运算符
+ - * / % ++ --
<!-- 重点强调++a 和 a++ 不同之处 --> <script> var b=7; b++; console.log(b); ++b; console.log(b); console.log(b++); console.log(++b); var c=8; var aa=7; var bb=10; c++;//9 aa=++aa+c;//17 console.log(aa++); console.log(aa); </script>
比较运算符
=== >= <= != !
<!-- 重点强调值比较 类型的比较 不同之处 --> <script> console.log('undefined==null',undefined==null); console.log('undefined===null',undefined===null); </script>
案例or练习 ?
逻辑运算符
&& || !
例:
<script> // 短路语句 console.log(1&&2&&4); </script>
案例or练习 ?
赋值元素符
+= -= *= /= =
三元运算符(重点)
条件?表达式1:表达式2
运算符优先级
一元运算符>算术运算符>比较运算符>逻辑运算符>三元运算符>赋值元素符
隐式转换
运算符中存在的隐式转换 + 转正数
+ 转正数 例题: +'s'+2 +'1'+1 - 转负数 例题: +'1'-1 '22'-2 * 转数值 例题: 3*'3' !转布尔值 例题 !true + 1 !!""+"33"
//讲解 例题1: var a;//undefined var b = a * 0;//b=NaN if (b == b) { console.log(b * 2 + "2" - 0 + 4); } else { console.log(!b * 2 + "2" - 0 + 4); //布尔值做数学运算时 // true*2=1*2=2+"2"="22"-0=22-0=22+4=26 // 注意:true++ 报错 true+1没问题 // console.log('true++',true++) } </script> <script> // 例题2 if(typeof(a) && -true + (+undefined)+""){ // true && NaN+""="NaN" console.log(2); }else{ console.log(1); } </script> <script> // 例题3 var res=!!" "+!!""-!!false || document.write("you"); // true+false-false=1-0-0=1 console.log(res); </script>
总结+的作用
1.在多元运算中与字符串在一起是连接符
2.一元运算符中转正数
3.和数值在一起做加法运算