iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 29
1

第一次看到 Truthy 和 Falsy 時,覺的這個寫法有點像是 Python 的寫法,除了 boolean 可以拿來判斷 true, false 之外,其他的型別可以拿來判斷!但與其不同的是,他的空陣列可不是 Truthy 喔。

雖然這個是 JavaScript 的功能,但由於 TypeScript 也包含了 JavaScript, 所以他一樣是有這個概念的,唯一著差別就是 TypeScript 沒有 NaN。(我想應該是沒有吧,如果我有說錯在麻煩各位大大們指正一下)

關於 Truthy 和 Falsy,他的概念其實很簡單,只要記的所有的物件都是 Truthy, 只有 空字串, 數字0, undefined 和 null 會是 Falsy, 其餘的都是 Truthy。

就讓我們寫個小程式來測試一下吧!!

function testTruthyFalsy(message: string, value: any) {
  if (value) {
    console.log(`"${message}" \t=> Truthy.`)
  } else {
     console.log(`"${message}" \t=> Falsy.`);
  }
}

// false 當然是 false 沒問題
testTruthyFalsy('boolean false', false);
// 可是, 由於所有物件都是 Truthy 的關係, 就算你是 false Boolean
// 結果也會是 Truthy 喔!!!這個要小心 (<- 感謝邦友 hung19091 幫忙糾錯 ^_^)
testTruthyFalsy('new Boolean(false)', new Boolean(false));

// 空字串是 Falsy
testTruthyFalsy('Empty string', '');
// 非空字串是 Truthy
testTruthyFalsy('new String("")', new String(''));

// undefined 和 null  都是 Falsy
testTruthyFalsy('undefined', undefined);
testTruthyFalsy('null', null);

// 除了 0 以外的數字都是 Truthy 喔
testTruthyFalsy('10', 10);
testTruthyFalsy('-10', -10);
testTruthyFalsy('0', 0);
testTruthyFalsy('new Number(0)', new Number(0));

// 管你是什麼物件,要記住他們都是 Truthy
// 就算是 Boolean(false) 也一樣
testTruthyFalsy('[]', []);
testTruthyFalsy('[1, 2]', [1, 2]);
testTruthyFalsy('{}', {});
testTruthyFalsy('{1:"super"}', {1:"super"});

輸出結果:

"boolean false"         => Falsy.
"new Boolean(false)"    => Truthy.

"Empty string"   => Falsy.
"new String("")" => Truthy.

"undefined"      => Falsy.
"null"           => Falsy.

"10"             => Truthy.
"-10"            => Truthy.
"0"              => Falsy.
"new Number(0)"  => Truthy.

"[]"             => Truthy.
"[1, 2]"         => Truthy.
"{}"             => Truthy.
"{1:"super"}"    => Truthy.

因為所有的物件都是 Truthy 的關係,所以一定要特別留意,就算是 Boolean(false) 他在 if 判斷之下,他也是 true 喔!!別一不小心就踩雷了!!

變數型別 Falsy 狀態 Truthy 狀態
boolean false true
string 空字串 除了空字串的任何字串
number 0 除了0以外任意值
null or undefine 永遠都是 不可能
任何物件,包含{} 或 [] 不可能 永遠都是

(from 深入理解 TypeScript)


上一篇
第28天-Promise在非同步的應用
下一篇
第30天-終點囉
系列文
從零開始進入 JavaScript & TypeScript 的世界 共 30 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
hung19091
iT邦新手 5 級 ‧ 2023-08-23 14:37:58

// 可是, 由於所有物件都是 Truthy 的關係, 就算你是 false Boolean
// 結果也會是 Falsy 喔!!!這個要小心

雖然考古了XD 提醒一下
註解的粗體字部份,應該是Truthy才對

pajace2001 iT邦研究生 1 級 ‧ 2023-08-23 15:00:56 檢舉

謝謝幫忙更正

我要留言

立即登入留言