邏輯與 (&&)
對於一組布林運算元,邏輯與 (&&)(邏輯合取)運算子當且僅當所有運算元為 true 時才為 true。否則為 false。
試一試
const a = 3;
const b = -2;
console.log(a > 0 && b > 0);
// Expected output: false
語法
js
x && y
描述
邏輯與 (&&) 從左到右評估運算元,遇到第一個假值運算元時立即返回其值;如果所有值都為真值,則返回最後一個運算元的值。
如果一個值可以轉換為 true,則該值被稱為真值 (truthy)。如果一個值可以轉換為 false,則該值被稱為假值 (falsy)。
可以轉換為 false 的表示式示例有:
false;null;NaN;0;- 空字串(
""或''或``); undefined.
AND 運算子保留非布林值並按原樣返回它們
js
result = "" && "foo"; // result is assigned "" (empty string)
result = 2 && 0; // result is assigned 0
result = "foo" && 4; // result is assigned 4
儘管 && 運算子可以與非布林運算元一起使用,但它仍被視為布林運算子,因為其返回值始終可以轉換為布林原始值。要顯式地將其返回值(或一般而言的任何表示式)轉換為相應的布林值,請使用雙重NOT 運算子或Boolean建構函式。
短路求值
邏輯與表示式是短路運算子。當每個運算元轉換為布林值時,如果其中一個轉換結果為 false,則 AND 運算子停止並返回該假值運算元的原始值;它不會評估任何剩餘的運算元。
請考慮以下虛擬碼。
(some falsy expression) && expr
expr 部分從不被評估,因為第一個運算元 (some falsy expression) 被評估為假值。如果 expr 是一個函式,則該函式從不被呼叫。請參閱下面的示例
js
function A() {
console.log("called A");
return false;
}
function B() {
console.log("called B");
return true;
}
console.log(A() && B());
// Logs "called A" to the console due to the call for function A,
// && evaluates to false (function A returns false), then false is logged to the console;
// the AND operator short-circuits here and ignores function B
運算子優先順序
AND 運算子的優先順序高於 OR 運算子,這意味著 && 運算子在 || 運算子之前執行(請參閱運算子優先順序)。
js
true || false && false; // true
true && (false || false); // false
(2 === 3) || (4 < 0) && (1 === 1); // false
示例
使用 AND
以下程式碼顯示了 &&(邏輯與)運算子的示例。
js
a1 = true && true; // t && t returns true
a2 = true && false; // t && f returns false
a3 = false && true; // f && t returns false
a4 = false && 3 === 4; // f && f returns false
a5 = "Cat" && "Dog"; // t && t returns "Dog"
a6 = false && "Cat"; // f && t returns false
a7 = "Cat" && false; // t && f returns false
a8 = "" && false; // f && f returns ""
a9 = false && ""; // f && f returns false
布林值轉換規則
AND 轉換為 OR
以下涉及布林值的操作
js
bCondition1 && bCondition2
始終等於
js
!(!bCondition1 || !bCondition2)
OR 轉換為 AND
以下涉及布林值的操作
js
bCondition1 || bCondition2
始終等於
js
!(!bCondition1 && !bCondition2)
移除巢狀括號
由於邏輯表示式從左到右求值,因此只要遵循某些規則,總是可以從複雜表示式中移除括號。
以下涉及布林值的複合操作
js
bCondition1 || (bCondition2 && bCondition3)
始終等於
js
bCondition1 || bCondition2 && bCondition3
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # prod-LogicalANDExpression |
瀏覽器相容性
載入中…