JavaScript 比较
JavaScript 比较运算符和逻辑运算符
Section titled “JavaScript 比较运算符和逻辑运算符”Comparison and logical operators are fundamental for making decisions and controlling the flow of execution in JavaScript programs. They evaluate to a Boolean value (true or false).
Comparison operators are used in logical statements to determine equality or difference between variables or values. It is highly recommended to use strict comparison operators (=== and !==) to avoid unexpected behavior due to type coercion.
Given let x = 5;
| Operator | Description | Example | Returns |
|---|---|---|---|
== | 等于(宽松相等 - 执行类型强制转换) | x == "5" | true(尽量避免使用) |
=== | 值相等且类型相等(严格相等) | x === "5" | false |
=== | 值相等且类型相等(严格相等) | x === 5 | true(推荐) |
!= | 不等于(宽松不等 - 执行类型强制转换) | x != "5" | false(尽量避免使用) |
!== | 值或类型不相等(严格不等) | x !== "5" | true |
!== | 值或类型不相等(严格不等) | x !== 5 | false(推荐) |
> | 大于 | x > 8 | false |
< | 小于 | x < 8 | true |
>= | 大于或等于 | x >= 5 | true |
<= | 小于或等于 | x <= 8 | true |
Understanding Type Coercion: Loose equality (==) attempts to convert operands to the same type before comparison, which can lead to counter-intuitive results (e.g., 0 == false is true, "" == false is true). Strict equality (===) does not perform type coercion; if types are different, it returns false.
在条件语句中使用比较运算符
Section titled “在条件语句中使用比较运算符”Comparison operators are commonly used in if, else if, while, and other control flow statements to make decisions.
const age = 20;let message;
if (age >= 18) { message = "Old enough to vote.";} else { message = "Too young to vote.";}console.log(message); // 输出: Old enough to vote.您将在专门的章节中学习更多关于条件语句的内容。
Logical operators are used to combine or invert Boolean values.
Given let x = 6; and let y = 3;
| Operator | Description | Example | Result |
|---|---|---|---|
&& | 逻辑与:如果两个操作数都为 true 则为 true | (x < 10 && y > 1) | true (true && true) |
&& | 逻辑与 | (x < 10 && y < 1) | false (true && false) |
| ` | ` | 逻辑或:如果至少一个操作数为 true 则为 true | |
| ` | ` | 逻辑或 | |
! | 逻辑非:反转布尔值 | !(x === y) | true (not false) |
! | 逻辑非 | !(x === 6) | false (not true) |
短路求值(Short-Circuiting):逻辑与(&&)和逻辑或(||)运算符具有短路行为。
对于 expr1 && expr2,如果 expr1 的结果为假值(falsy),则不再评估 expr2。
对于 expr1 || expr2,如果 expr1 的结果为真值(truthy),则不再评估 expr2。这常用于条件执行或设置默认值。
使用逻辑或(||)进行短路求值设置默认值的示例:
const userName = null;const displayName = userName || "Guest"; // displayName 将是 "Guest"The Nullish Coalescing Operator (??) (ES2020) is a related logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. This is useful for providing defaults for variables that might be intentionally 0 or false.
const count = 0;const displayCount = count ?? 10; // displayCount 是 0 (0 不是 null 也不是 undefined)
const userSetting = null;const defaultSetting = userSetting ?? { theme: 'dark' }; // defaultSetting 是 { theme: 'dark' }条件(三元)运算符
Section titled “条件(三元)运算符”The conditional (ternary) operator is a concise way to write simple if-else statements.
condition ? valueIfTrue : valueIfFalse
const userAge = 17;const canVote = (userAge >= 18) ? "Can vote" : "Cannot vote";console.log(canVote); // 输出: Cannot voteIf userAge >= 18 is true, canVote is assigned “Can vote”; otherwise, it’s assigned “Cannot vote”.
比较不同类型
Section titled “比较不同类型”Comparing data of different types using loose equality (==) can lead to unexpected results due to type coercion. It’s generally safer to use strict equality (===) or explicitly convert types before comparison.
When comparing two strings, JavaScript performs lexicographical (alphabetical) comparison: "2" > "12" is true because ‘2’ comes after ‘1’ alphabetically.
为了确保进行数值比较,将字符串转换为数字:
let ageInput = "25"; // from a form input, for examplelet ageNumber = Number(ageInput);let isAdult;
if (isNaN(ageNumber)) { isAdult = "Invalid input";} else { isAdult = (ageNumber >= 18) ? "Adult" : "Minor";}console.log(isAdult); // 输出: AdultNumber() 将空字符串 "" 转换为 0,将非数字字符串(无法转换的)转换为 NaN(Not a Number,非数字)。使用 isNaN() 来检查是否为 NaN。 |
|---|
JavaScript 位运算符
Section titled “JavaScript 位运算符”Bitwise operators treat their operands as sequences of 32 bits (zeros and ones) and perform operations on them bit by bit. These are less common in everyday web development but are used in some specific scenarios like graphics programming, data compression, or working with low-level protocols.
Operands are converted to 32-bit signed integers before the operation, and the result is converted back to a JavaScript number.
| Operator | Description | Example (Simplified Binary) |
|---|---|---|
& | 按位与 | 5 & 1 (0101 & 0001) -> 1 (0001) |
| ` | ` | 按位或 |
^ | 按位异或 | 5 ^ 1 (0101 ^ 0001) -> 4 (0100) |
~ | 按位非(反转所有位) | ~5 (~0…0101) -> -6(在二进制补码中是 1…1010) |
<< | 左移(将位向左移动,右侧填充 0) | 5 << 1 (0101 << 1) -> 10 (1010) |
>> | 有符号右移(将位向右移动,左侧填充符号位) | 5 >> 1 (0101 >> 1) -> 2 (0010) |
>>> | 无符号右移(将位向右移动,左侧填充 0) | 5 >>> 1 (0101 >>> 1) -> 2 (0010) |
注意:JavaScript 位运算使用 32 位有符号二进制补码表示。这意味着 ~5 的结果是 -6,而不是像一个简单的 4 位无符号示例可能表明的 10。理解二进制补码对于理解 ~ 和 >> 很关键。 |
|---|