逻辑运算符

1. 概念

概念∶逻辑运算符是用来进行布尔值运算的运算符,其返回值也是布尔值。后面开发中经常用于多个条件的判断

 

 

逻辑 && 与

 

 逻辑 || 或

 

逻辑 ! 非

就是取反

2. js 代码

        // 1. 逻辑与 &&  and 两侧都为true  结果才是 true  只要有一侧为false  结果就为false 
        console.log(3 > 5 && 3 > 2); // false
        console.log(3 < 5 && 3 > 2); // true
        // 2. 逻辑或 || or  两侧都为false  结果才是假 false  只要有一侧为true  结果就是true
        console.log(3 > 5 || 3 > 2); // true 
        console.log(3 > 5 || 3 < 2); // false
        // 3. 逻辑非  not  ! 
        console.log(!true); // false

 

 3. 短路运算 (逻辑中断)

 短路运算的原理∶当有多个表达式(值)时,左边的表达式值可以确定结果时,就不再继续运算右边的表达式的值;

 

 

 

 

 js 代码

        // 1. 用我们的布尔值参与的逻辑运算  true && false  == false 
        // 2. 123 && 456  是值 或者是 表达式 参与逻辑运算? 
        // 3. 逻辑与短路运算  如果表达式1 结果为真 则返回表达式2  如果表达式1为假 那么返回表达式1
        console.log(123 && 456); // 456
        console.log(0 && 456); //  0
        console.log(0 && 1 + 2 && 456 * 56789); // 0
        console.log('' && 1 + 2 && 456 * 56789); // ''
        // 如果有空的或者否定的为假 其余是真的  0  ''  null undefined  NaN
        // 4. 逻辑或短路运算  如果表达式1 结果为真 则返回的是表达式1 如果表达式1 结果为假 则返回表达式2
        console.log(123 || 456); // 123
        console.log(123 || 456 || 456 + 123); // 123
        console.log(0 || 456 || 456 + 123); // 456
        // 逻辑中断很重要 它会影响我们程序运行结果思密达
        var num = 0;
        console.log(123 || num++);
        console.log(num); // 0

 

posted @ 2022-04-03 11:06  会前端的洋  阅读(356)  评论(0)    收藏  举报