首页 > 代码库 > js之&& || & |

js之&& || & |

1.

function f1(){
  return 0;  
}

function f2(){
  return 1;  
}

console.log(f1() && f2()); // 0
console.log(f1() || f2()); // 1
console.log(f2() && f1()); // 0
console.log(f2() || f1()); // 1

&&以及||具有短路性质的逻辑运算符

  左操作数 && 右操作数:

    当左操作数为真时,整个表达式的值即为右操作数的值;

    当左操作数为非真时,此刻右操作数将不做运算,整个表达式的值即为左操作数的值。

  

  左操作数 || 右操作数:

    当左操作数为真时,此刻右操作数将不做运算,整个表达式的值即为左操作数的值;

    当左操作数为非真时,整个表达式的值即为右操作数的值;;

2.

console.log((1 && 2 || 0) && 3); //3 分析1
console.log(1 && 2 || 0 && 3); //2 分析2
console.log(0 && 1 || 2 && 3); //3 分析3

分析1:1 && 2 返回2,然后 2 || 0 返回2,然后 2 && 3 返回3
分析2:1 && 2 返回2,然后 0 && 3 返回0,然后 2 || 0 返回2
分析3:0 && 1 返回0,然后 2 && 3 返回3,然后 0 || 3 返回3

3.

function f1(){
    console.log("f1");
    return 0;      
}
function f2(){
    console.log("f2");
    return 0;      
}
function f3(){
    console.log("f3");
    return 0;      
}
function f4(){
    console.log("f4");
    return 0;      
}
        
if(f1() & f2() & f3() & f4() ){
    console.log(‘OK‘);
}
if(f1() | f2() | f3() | f4() ){
    console.log(‘YES‘);
}

| 和 &是位运算,不具有短路性质

js之&& || & |