## JS 邏輯運算子 JS 中使用邏輯運算子,可以讓一些邏輯判斷寫法更簡潔。 ## Truthy / Falsy 在了解邏輯運算子前,要先理解什麼是 **`Truthy` `Falsy`**,簡單來說就是透過 Boolean() 將值轉成布林值 True False 值,邏輯運算子是根據 truthy falsy 去運作。 ### Truthy ``` Boolean(true) Boolean('0') // 這裡的 0 是字串所以會是有值 Boolean(20) Boolean(['a', 'b', 'c']) Boolean([]) Boolean({name: 'nono'}) Boolean({}) ``` ### Falsy ``` Boolean(false) Boolean(0) Boolean('') Boolean(null) Boolean(undefined) Boolean(NaN) ``` ## 邏輯運算子 ### && 運算符 `&&` 運算符用於邏輯 AND 運算以左至右,回傳遇到的第一個 falsy;如果全部都是 true 就會回傳最後一個值。 ``` const x = 5; const y = 10; const outPut = x > 1 && y > 1; // true const outPut2 = x < 1 && y > 1; // false ``` ### || 運算符 `||`運算符用於邏輯 OR 運算以左至右,回傳第一個 truthy,如果所有的都是 falsy 的,則回傳最後一個值。 ``` const x = 5; const y = 0; const outPut1 = x || y; // 5 const outPut2 = y || x; // 5 ``` ### ?? 運算符 `??` 運算符稱為 null 合併運算符。用於處理可能為 null 或 undefined 的值,以左至右回傳第一個不是 null 或 undefined 的值,如果兩個操作數都是 null 或 undefined,它將返回右側的值。 ``` const v = 10 const w = 0 const x = null; const y = undefined; const outPut1 = x ?? v; // 10 const outPut2 = x ?? y ?? w ?? 10; //0 const outPut3 = x ?? v ?? y; //10 ```
×
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