二、JS 基础知识之流程控制(2)--- 比较运算符、逻辑运算符、运算符优先级

97 阅读2分钟

(4)比较运算符

比较运算符 是用来比较两个数据的大小、是否相等,比较的结果是 布尔类型 ,就是说只会得到 truefalse

image.png

= 、== 、=== 的区别:

  • = 是赋值操作,将右边的值赋值给左边,左边必须是变量
  • == 是判断,只要值相等就可以返回 true ,不用管数据类型
  • === 是全等,值和数据类型都要一样才能能返回 true ,开发中推荐使用全等

需要注意的是,字符串比较 中,比较的是字符对应的 ASCII 码 ,从左往右依次比较,直至得出结果,不过字符串比较平时用的比较少,了解一下即可。

  <body>
    <script>
      console.log('a' > 'b')
      console.log('abcd' > 'abdc')
      console.log('ab' > 'a')
      console.log('ab' > 'abcd')
    </script>
  </body>

image.png

image.png

另外,NaN 不等于任何值,包括它本身:

  <body>
    <script>
      console.log( 'a' === NaN )
      console.log( 123 === NaN )
      console.log( NaN === NaN )
    </script>
  </body>

image.png

因为小数会有精度问题,所以 尽量不要比较小数

  <body>
    <script>
      console.log( 0.1 + 0.2 === 0.3 )
      console.log( 0.1 + 0.2 )
    </script>
  </body>

image.png

不同类型之间比较会发生隐式转换,因此在进行数值之间的比较时,最好把数值转换成 number 类型再比较

如果要进行精准的比较,大多数情况下我们会选择全等 ===

(5)逻辑运算符

逻辑运算符 用来解决多重条件判断,例如我们想要得到成绩大于 60 并且 小于 80 分的为良好,在数学中可以写为 60 < 成绩 <80 ,但在程序中没有这种写法,对于这种情况,逻辑运算符恰到好处:

  <body>
    <script>
      let math = 65
      if (math > 60 && math < 80) {
        console.log('良好')
      }
    </script>
  </body>

image.png

逻辑运算符及用法如下所示:

image.png

逻辑运算符里的 短路 只存在于 && 和 || 中,当满足一定条件时会让右边代码不执行:

  • && : 左边为 false 就短路;
  • || : 左边为 true 就短路。

短路是因为通过左边能得到整个式子的结果,因此没有必要再去判断后面的

无论是 && 还是 || ,运算的结果都是最后被执行的表达式的值,一般用在变量赋值

  <body>
    <script>
      console.log(false && 20)
      console.log(5 < 5 && 12)
      console.log(undefined && 12)
      console.log(null && 12)
      console.log(0 && 12)
      console.log(11 && 12)
    </script>
  </body>

image.png

  <body>
    <script>
      console.log(false || 20)
      console.log(5 < 5 || 12)
      console.log(undefined || 12)
      console.log(null || 12)
      console.log(0 || 12)
      console.log(11 || 12)
    </script>
  </body>

image.png

有 5 个值可以当作 false 来看的,其余均为 true :false 、数字 0 、'' 、undefined 、null ,上例中,&& 不短路以后边的为准,|| 短路以前边的为主

  <body>
    <script>
      function add(x, y) {
        console.log('*********************************')
        console.log(x + ' ' + y)
        x = x || 0
        y = y || 0
        x + y
        console.log('*********************************')
        console.log(x + ' ' + y)
      }
      add() // 函数调用的时候没有传值,x,y 为 undefined
    </script>
  </body>

image.png

(6)运算符优先级

image.png

image.png