布林值可能是 Number、String、Boolean 三種包裝物件中最簡單的一種。Number 與 String 擁有大量實例屬性與方法,Boolean 卻很少。從某個角度看,寫程式就是與布林值打交道——所有電子電路本質上只能辨識兩種狀態。
定義
Boolean 型別表示邏輯實體,只有兩個值:保留字 true 與 false,分別代表真與假。
Boolean 包裝型別是對應的引用型別,在布林表達式中使用 Boolean 物件容易造成誤解:
var b1 = true;
var b2 = new Boolean(true);
console.log(b1, typeof b1); // true 'boolean'
console.log(b2, typeof b2); // Boolean{[[PrimitiveValue]]: true} 'object'
console.log(b1.valueOf(), typeof b1.valueOf()); // true 'boolean'
console.log(b2.valueOf(), typeof b2.valueOf()); // true 'boolean'
注意 typeof b2 是 'object' 而非 'boolean',這正是誤解的來源。
應用場景
【1】條件與迴圈語句。布林值主要出現在 if、while、for 的條件部分。實務上常把建立布林值的比較直接寫進條件裡:
if (a > 1) {
// 條件為 true 時執行
} else {
// 條件為 false 時執行
}
【2】邏輯運算子。邏輯非運算子總是回傳布林值,而邏輯或與邏輯與則不一定。連續兩個驚嘆號可以把值轉為布林:
console.log(!!1); // true console.log(!!0); // false console.log(!!' '); // true console.log(!!''); // false
【3】關係運算子。關係運算子測試兩個值之間的關係,依關係是否存在回傳 true 或 false,運算結果一定是布林值:
console.log(1 > 2); // false console.log(1 < 2); // true
轉為布林:假值與真值
用 Boolean() 轉型函式可以明確轉換。轉換後為 false 的值稱為假值(falsy),共 7 個:
console.log(Boolean(undefined)); // false
console.log(Boolean(null)); // false
console.log(Boolean(0)); // false
console.log(Boolean(-0)); // false
console.log(Boolean(NaN)); // false
console.log(Boolean('')); // false
console.log(Boolean(false)); // false
注意:Number() 會把空字串與空白字串都轉為 0,但 Boolean() 只把空字串轉為 false,空白字串 ' ' 是 true。
console.log(Number('')); // 0
console.log(Number(' ')); // 0
console.log(Boolean('')); // false
console.log(Boolean(' ')); // true
除了這 7 個假值,其餘都是真值(truthy)。
注意:所有物件(包括空物件)轉布林都是 true,連 new Boolean(false) 也不例外:
console.log(Boolean({})); // true
console.log(Boolean([])); // true
console.log(Boolean(new Boolean(false))); // true
console.log(Boolean(false)); // false
console.log(Boolean(new Boolean(null))); // true
console.log(Boolean(null)); // false
這個特性有個著名的實作陷阱:
var flag = new Boolean(false);
if (flag) {
// 這裡會執行!因為 flag 是物件,永遠為真
}
要判斷值本身,得先取出原始值:if (flag.valueOf()) 或直接比較 flag == false。
實例方法
Boolean 物件繼承了 Object 的三個通用方法:
toString() 回傳字串 'true' 或 'false';toLocaleString() 同樣回傳 'true' 或 'false';valueOf() 回傳原始的布林值。
console.log(true.valueOf()); // true console.log(true.toString()); // 'true' console.log(true.toLocaleString()); // 'true' console.log(Boolean(false).valueOf()); // false console.log(Boolean(false).toString()); // 'false' console.log(Boolean(false).toLocaleString()); // 'false'
實務結論很明確:判斷真假時直接使用原始布林值,避免 new Boolean()。它幾乎沒有實際用途,反而容易在條件判斷中造成難以察覺的 bug。