1. 逻辑与(&&)
    • 语法和用法:在 ArkTS 中,逻辑与运算符是 “&&”。它用于连接两个布尔表达式,当且仅当两个表达式的值都为true时,整个逻辑与表达式的值才为true。例如:
         let a: boolean = true;
         let b: boolean = false;
         let result: boolean = a && b;
         // result的值为false,因为a为true,b为false,根据逻辑与运算规则,只有两个值都为true时结果才为true
    • 短路特性:逻辑与具有短路特性。如果第一个操作数为false,则不会计算第二个操作数。例如:
         function expensiveCheck(): boolean {
             console.log("执行了expensiveCheck函数");
             return true;
         }
         let condition1: boolean = false;
         let condition2: boolean = condition1 && expensiveCheck();
         // 因为condition1为false,所以expensiveCheck函数不会被执行,condition2的值为false
    1. 逻辑或(||)
      • 语法和用法:逻辑或运算符是 “||”。当两个布尔表达式中至少有一个为true时,整个逻辑或表达式的值为true。例如:
           let c: boolean = false;
           let d: boolean = true;
           let result2: boolean = c || d;
           // result2的值为true,因为c为false,d为true,根据逻辑或运算规则,只要有一个值为true结果就为true
      • 短路特性:逻辑或也有短路特性。如果第一个操作数为true,则不会计算第二个操作数。例如:
           function anotherExpensiveCheck(): boolean {
               console.log("执行了anotherExpensiveCheck函数");
               return false;
           }
           let condition3: boolean = true;
           let condition4: boolean = condition3 || anotherExpensiveCheck();
           // 因为condition3为true,所以anotherExpensiveCheck函数不会被执行,condition4的值为true
      1. 逻辑非(!)
        • 语法和用法:逻辑非运算符是 “!”,它是一个一元运算符,用于对一个布尔表达式取反。如果操作数为true,则逻辑非运算后的结果为false,反之亦然。例如:
             let e: boolean = true;
             let result3: boolean =!e;
             // result3的值为false,因为对true取反得到false

Logo

社区规范:仅讨论OpenHarmony相关问题。

更多推荐