逻辑与 (&&)
对于一组布尔操作数,逻辑与 (&&)(逻辑合取)运算符当且仅当所有操作数为 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 |
浏览器兼容性
加载中…