--- title: 'JS 核心 8 - Truthy 與 Falsy' tags: JS 核心, Javascript, Truthy 與 Falsy description: 2021/02/04 --- JS 核心 -- Truthy 與 Falsy === ## Truthy 與 Falsy * **Truthy**:在布林值的判斷裡面,轉換後的值 * [**對照 "if 真值表"**](https://dorey.github.io/JavaScript-Equality-Table/) : 綠色代表 Truthy * <span class="red">這裡的**真值 truthy、假值 falsy** 不要和**隱含轉型的true、false** 搞混,是不一樣的</span> ``` if (判斷式){ ... 只要 (判斷式) 為真值 truthy,就執行 } ``` ``` if (undefined) { console.log('執行程式'); } else { console.log('執行 Else'); // 執行 Else }; if (0){ console.log('執行程式'); } else { console.log('執行 Else'); // 執行 Else }; ``` 空物件、空陣列 - 屬於 truthy ``` if ({}) { console.log('執行程式'); // 執行程式 } if ([]) { console.log('執行程式'); // 執行程式 } ``` 只要字串內有內容,皆為 truthy ```typescript if ('') { console.log('執行程式'); } else { console.log('執行 Else'); // 執行 Else }; // 字串 ‘ ’ 中加入空白鍵 if (' ') { console.log('執行程式'); // 執行程式 } else { console.log('執行 Else'); }; ``` 只要是物件的型式,不管內容是什麼,皆為 truthy ``` console.log(new Boolean(false)); // Boolean {false} if (new Boolean(false)) { console.log('執行程式'); // 執行程式 } else { console.log('執行 Else'); } ``` 雖然 Number 的數字是 0,Number 是一個物件的型式,物件就算是空物件也是屬於 truthy。 ``` console.log(new Number(0)); // Number {0} if ( new Number(0) ){ console.log('執行程式'); // 執行程式 } else { console.log('執行 Else'); }; ``` ✏ <span class="red">總結 : 在使用原始型別時,要避免使用包裹物件的方式來建立原始型式。</span> ### ☞ ToBoolean Truthy 與 Falsy 的概念,在 JavaScript 中會是 **false 值**如下 * "" ‒ 空字串 * 0、 -0、 NaN * null * undefined * false 除了以上之外,其餘都會被轉為 true,但其中比較特殊的如下 (以下都是 Truthy) * [ ] * { } * function foo ( ) { } ‒ 函式 * '0' ‒ 文字的 0 ( 字串裡面有內容,皆為 Truthy ) * ' ' ‒ 包含空白的引號 ( 字串裡面有內容,皆為 Truthy ) ## :memo: 學習回顧 :::info * **Truthy**:在布林值的判斷裡面,轉換後的值 * 字串裡面有內容 (包含空白字元),皆為 Truthy * [ ] 空陣列 * { } 空物件 * **Falsy** : "" 空字串、0、 -0、 NaN、null、undefined、false * <span class="red">這裡的**真值 truthy、假值 falsy** 不要和**隱含轉型的true、false** 搞混,是不一樣的</span> * 在使用原始型別時,要避免使用包裹物件的方式來建立原始型式。 ::: ## :+1: 相關參考文件 :::info [KURO -「比較」與自動轉型的規則](https://ithelp.ithome.com.tw/articles/10191254) ::: <style> .red { color: red; } .green { color: green; } </style>
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.