JavaScript运算符(二)相等、全等、赋值、关系操作符、条件操作符(即三元表达式)

JavaScript运算符

相等操作符

相等操作符再JavaScript中主要用于判断等号两边的内容是否相等,使用’=='来表示。

null和undefined可以相等,(null==undefined)也可以与自身相等,除此之外,与任何值都不相等 。

null和undefined除了自身和对方之外,跟任何值比较都是false。

NaN不参与比较,也不参与运算。

如:

	console.log(1 == 12); //false
    console.log('str1' == 'str2'); //false
    console.log(5 == 5); //true
    console.log(true == true); //true
    console.log(null == undefined); //true
    console.log(null == 1); //false
    console.log(NaN == 'str'); //false
    console.log(true == 1); //true

全等操作符

全等操作符用===表示。全等操作符两边的数据类型要相同,也要相同。

操作原则:

  1. 符号两边的数据类型要相同
  2. 符号两边的值要相等
  3. NaN不与任何值相等

!= 是对 ==的值取反

!== 是对 ===的值取反

如:

  	console.log(1 == '1'); //true
    console.log(1 === '1'); //false
    console.log(null == undefined); //true
    console.log(null === undefined); //false
    console.log('1' != 1); //false 不相等
    console.log('1' !== 1); //true  不全等

关系操作符

关系操作符有大于>、小于<、大于等于>=、小于等于<=,用于对两个值进行比较。返回的值都是布尔值,即不是true就是false。

操作原则:

  1. NaN不管和谁比都是false
  2. 都是字符串时,通过ASCII码比较(ASCII编码表上有对应的编码,使用时直接去查找即可)
  3. 如果是中文比较,则比较unicode编码(unicode编码表上有对应中文的编码)
  4. 如果有个操作数是布尔值 ,则先将布尔值转换成数值再比较
  5. 如果一个操作数是数值 ,另一个不是数值,则将另一个数通过Number转换成数值以后再比较

如:

    console.log(1 < '2d'); //false
    console.log(NaN <= 1); //false
    console.log('a' < 'b'); //true 如a的ascii码值为61,b的ascii值为62,因为61<62,所以a<b
    console.log('aB' > 'Ab'); //true 先比较a和A A的ascii值为41 61>41所以 aB>Ab
    console.log('我' > '你'); //true 如你的Unicode编码为4F60 我的Unicode编码为6210 显然6210>4f60 所以'我'>'你'

赋值操作符

赋值操作符即将符号右边的值赋给左边,使用=来表示。

注意:在赋值的瞬间,左边的值要固定。如:不能是a++因为是不固定的。

  • 乘/赋值(*=)
  • 除/赋值(/=)
  • 加/赋值(+=)
  • 减/赋值(-=)
  • 模/赋值(%=)

如:

    var a = 1;
    var b = 2;
    a = b; //将b的值赋给a
    console.log(a); //2
    console.log(b); //2
    b += 2; //b = b + 2
    console.log(b); //4
    var c = 4;
    c += '2'; //c = c +'2' 字符串相加
    console.log(c); //42
    console.log(typeof c); //string

条件操作符

在有些编程语言里面条件操作符也叫三目运算符[三元表达式]。它的基本语法如下:

表达式?表达式1:表达式2
//当表达式为true时,执行表达式1,否则执行表达式2
// 当表达式的结果不为boolean时,我们需要用Boolean()去测试
//牢记boolean值为false的类型:NaN 0 '' undefined null false

三元表达式也可以进行嵌套,如:

( 表达式?表达式1:表达式2)?( 表达式?表达式1:表达式2):( 表达式?表达式1:表达式2)

如:

	console.log(2 > 3 ? 2 : 3); //3
    console.log(false ? true : false); //false
//求出a,b,c三个值中的最大值
    var a = 12,//此处有逗号操作符,即代表一个操作没有结束
        b = 14,
        c = 2;
    var max1 = (a > b) ? a : b; //14
    var max2 = max1 > c ? max1 : c; //14
    console.log(max1);
    console.log(max2);
    //嵌套
    console.log(((a > b) ? a : b) > c ? ((a > b) ? a : b) : c);//14

猜你喜欢

转载自blog.csdn.net/weixin_42567822/article/details/124931060