运算符的使用

运算符的应用

1.赋值运算符

var username ="tom";//简单赋值运算符
复合运算符
a+=b;//相当于a=a+b
a-=b;//相当于a=a-b
a=b;//相当于a=ab
a/=b;//相当于a=a/b
a%=b;//相当于a=a%b
a&=b;//相当于a=a&b
a|=b;//相当于a=a|b
a=b;//相当于a=ab

2.算数运算符

+,-,*,/,%,
++
i=1;j=i++;//j是1,i是2。 因为 i++是先用后加
i=1;j=++i;//j是2,2是2。 因为++i是先加后用
--同理
除法运算时,0不能为除数,如果0为除数,则会返回Infinity
function f03() {
console.log(1/0); //Infinity
}

3.比较运算符

<
>
<=
>=
== 判断表面值是否相等 alert("11"11) 返回true
=== 不仅判断表面值还判断数据类型
!= 判断值
!
不仅判断表面值还判断数据类型

逻辑运算符

! 逻辑非
&& 逻辑与
|| 逻辑或
逻辑"与"短路运算,如果表达式1为真,则返回表达式2,如果表达式1为假则返回表达式1
console.log(123 && 456);//输出456
console.log(0 && 456);//输出0
逻辑"或"短路运算,如果表达式1为真,则返回表达式1,如果表达式1为假则返回表达式2
console.log(123 || 456);//输出123
console.log(0 || 456);//输出456

条件运算符

三元运算符
语法格式:操作数?结果1,结果2;
如果操作数的值为true 结果1
如果操作数的值为false 结果2
console.log(1>2?1:2); 输出 2
案例:
/*
三元表达式,数字补0;
*/
var num = prompt('输入数字')
var srt =num<10?num=0+num:num;
alert(srt);

字符串运算符

连接字符串的两种方式 +,+=
var name="hello"+"world";
name+="hello everyone";
console.log(name);
//输出helloworldhello everyone

posted @ 2023-04-11 17:49  摆烂员  阅读(113)  评论(0)    收藏  举报