# Boolean 的真假判斷 ### 逗號運算子 ```javascript= var a = 10; var b = 10; // 可以寫成 var a = 10, b = 10; ``` 這樣就可以同時宣告多組變數,且給予預設值。 但是,需要注意的地方是,可能有人會寫成這樣: ```javascript= var a = b = 10; console.log(a); // 10 console.log(b); // 10 ``` 但這樣會出問題,沒有 var 宣告的變數都會變成「全域變數」,將程式碼拆開來看 ```javascript= b = 10; var a = b; ``` 實際上變數b是沒有透過var來做宣告的。 在無意見創造了一個全域變數 ```javascript= (function(){ var a = b = 10 console.log(a, b); // 10, 10 })(); // 離開了變數作用範圍的 a 會變成 undefined // 而 b 卻變成全域變數而保留了狀態 console.log(a, b); // undefined, 10 ``` ### 邏輯運算子 (Logical Operator) ```javascript= var a = 123; var b = "abc"; var c = null; console.log( a && b ); // "abc" console.log( a || b ); // 123 console.log( c && a ); // null console.log( c || b ); // "abc" console.log( c || a ); // 123 ``` * 「AND &&」:當 && 左右兩側的值同時為 true 時,則會得到 true 的結果。 若其中一方是 false 的情況下,則得到 false 。 * 「OR ||」:當 || 左右兩側的值只要有一方為 true,則結果為 true。 只有在兩側皆為 false 的情況下才會得到 false 。 * 「NOT !」:以一個 ! 驚嘆號來表示,原本是 true 的結果經過 ! 轉換後會得到 false,而 false 會變成 true。 所以你可能會看到很多人用 !!xxx 來取代 Boolean(xxx),透過兩次的「NOT」操作,即可判斷某數值 Boolean 轉換後的結果。 **嚴格來說,只有「NOT !」運算子才會回傳 <font color="red">true</font>或 <font color="red">false</font>。** ### Falsy 與 Truthy: 論 Boolean 的型別轉換 * 那些經過 ToBoolean 轉換後得到 false 的值 * 以及其他的值,通常這些最後都會變成 true 分成兩種「值」,第一種就是經過 ToBoolean 轉換後會變成 <font color="red">false</font> 的部分: * Undefined * Null * +0, -0, or NaN * 空字串 "" 或 '' 那麼透過 <font color="red">ToBoolean</font> 轉換就會變成 <font color="red">false</font>,而其他的部分都會是 <font color="red">true</font>。 而那些轉換後會得到 <font color="red">false</font> 結果的,我們通常稱這些叫 **「falsy」值**,而其他會變成 <font color="red">true</font> 的部分,則是 **「truthy」**值。 **&& 與 || 運算子在判斷的時候,會先對左邊的數值進行檢查。** * 如果是 Boolean 類型就再做後續的判斷,如果不是?那就會透過 ToBoolean 判斷是「falsy」或「truthy」來轉換成對應的 true 跟 false 。 * 對 || 運算子來說,若第一個數值轉換為 true,**則回傳第一個數值**,否則回傳第二個數值。 * 對 && 運算子來說,**若第一個數值轉換為 true,則回傳第二個數值**,否則回傳第一個數值。 所以,在 if 條件判斷當中,JavaScript 會針對回傳後的數值再度做 ToBoolean 判斷是「falsy」或「truthy」, 這也就是為什麼在 && 與 || 的結果可以用來當作 true 與 false 的判斷了。 [參考資料:重新認識 JavaScript: Day 08 Boolean 的真假判斷](https://ithelp.ithome.com.tw/articles/10191343)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up