`truthy` 和 `falsy` 在 TypeScript 中的使用

`truthy` 和 `falsy` 在 TypeScript 中的使用

在本文中,我們將解釋 TypeScript 中的 truthyfalsy

YouTube Video

truthyfalsy 在 TypeScript 中的使用

TypeScript 中的 truthyfalsy 概念在程式的條件語句中扮演著非常重要的角色。在這裡,我們將詳細解釋這些概念及其實際使用方式。此外,我們將提供具體的 TypeScript 程式碼範例來了解如何處理 truthyfalsy 的值。

truthyfalsy 是什麼?

在 JavaScript 和 TypeScript 中,任何值在條件表達式中都會評估為 true(true)或 false(false)。這些值邏輯上被分類為 truthyfalsy

  • truthy” 指的是在條件表達式中被判定為 true 的值。
  • falsy” 指的是在條件表達式中被判定為 false 的值。

在 TypeScript 中,下列值被視為 falsy:。

  1. 數字 0
  2. ""(空字串)

所有其他值都被視為 truthy

「真值」和「假值」的具體例子

 1// Examples of falsy values
 2console.log("0 is", Boolean(0) ? "truthy" : "falsy");
 3console.log('"" is', Boolean("") ? "truthy" : "falsy");
 4console.log("null is", Boolean(null) ? "truthy" : "falsy");
 5console.log("undefined is", Boolean(undefined) ? "truthy" : "falsy");
 6console.log("NaN is", Boolean(NaN) ? "truthy" : "falsy");
 7
 8// Examples of truthy values
 9console.log("1 is", Boolean(1) ? "truthy" : "falsy");
10console.log('"hello" is', Boolean("hello") ? "truthy" : "falsy");
11console.log("[] is", Boolean([]) ? "truthy" : "falsy");
12console.log('" " (space) is', Boolean(" ") ? "truthy" : "falsy");

使用「真值」和「假值」的條件語句

truthyfalsy 的概念經常用於條件語句與迴圈中。例如,在 if 語句或 while 迴圈中,你可以直接使用這些值來進行簡單的條件評估。

 1// Checking if the length of the array is 0
 2let items: string[] = [];
 3
 4if (items.length) {
 5    console.log("The array is not empty");
 6} else {
 7    console.log("The array is empty");
 8}
 9
10// Checking if the input value is empty
11let input = "";
12
13if (input) {
14    console.log("Input has value");
15} else {
16    console.log("Input is empty"); // This will be executed
17}

使用 ??(空值合併)和 ||(邏輯或)處理「假值」

在 TypeScript 中,處理 falsy 值時有數個實用的運算符。特別是,通常使用空值合併運算符 (??) 和邏輯或運算符 (||)。

||(邏輯 OR)

邏輯或運算符用於將 falsy 值替換為默認值。然而,所有被認為是 falsy 的值(不僅僅是 nullundefined,還包括 0 和空字符串 "")也會被包括在內。

1let username = "";
2let displayName = username || "Guest";
3// Since username is empty, "Guest" is assigned
4
5console.log(displayName); // "Guest"

??(Nullish Coalescing)

空值合併運算子僅將預設值應用於 nullundefined,並將其他 falsy 值(如 0 或空字符串 "")保留原樣。

1let username2 = "";
2let displayName2 = username2 ?? "Guest";
3// The empty string is retained
4// since username2 is not null or undefined
5
6console.log(displayName2); // ""

與「真值」和「假值」相關的陷阱

在理解「truthy」和「falsy」時需要注意的一個重要點是,非預期的值可能會被視為「falsy」。例如,「0」和空字串「""」是有效值,但在條件語句中被視為「falsy」,這可能導致錯誤的評估結果。

1let score = 0;
2
3if (score) {
4    console.log("You have a score!"); // This will not be executed
5} else {
6    console.log("No score available"); // This will be executed
7}

在這種情況下,使用嚴格比較運算符可以準確區分類似 0false 的值。

1let score = 0;
2
3if (score === 0) {
4    console.log("Score is zero"); // Correctly evaluated
5}

falsyNaN 有關的陷阱

使用比較運算符時,NaN 需要特殊處理,因為它不等於任何值,包括它自身。

1console.log("NaN === NaN:", NaN === NaN); // false

因此,使用 Number.isNaN() 來準確檢測 NaN 更為安全。

 1// Bad Example
 2let value = parseInt("0");
 3if (!value) {
 4    console.log("Value is NaN(Incorrect)"); // Incorrectly treats 0 as NaN
 5}
 6
 7// Good Example
 8let value2 = parseInt("hello");
 9if (Number.isNaN(value2)) {
10    console.log("Value is NaN(Correct)"); // Correctly identifies NaN
11}

因此,NaN 甚至不等於它自身,與 NaN 的比較總是返回 false。通過使用 Number.isNaN(),您可以執行更可靠的檢測。

結論

TypeScript 中的「truthy」和「falsy」概念非常方便,但需要注意某些值,尤其是「0」和空字串。在條件檢查中使用這些值時,使用嚴格比較 (===) 或空值合併運算符 (??) 而不是寬鬆比較 (==) 可以幫助避免意外行為。

您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。

YouTube Video