close

驚嘆號(!)是個邏輯運算符,名稱為”Logic NOT”,用在布林值上具有反轉(Inverted)的功能,雙驚嘆號(!!)就等於”反轉再反轉“,等於轉回原本的布林值:

const aBool = true
const bBool = !aBool // false
const cBool = !!aBool // true


雙驚嘆號(!!)並不單純是在這樣用的,它是為了要轉換一些可以形成布林值的情況值,列出如下:
false: 0, -0, null, false, NaN, undefined, ''(空白字串)
true: 不是 false 的其他情況

const aBool = !!0 // false
const bBool = !!'false' // true
const cBool = !!NaN // false


經過雙驚嘆號運算後,只會很單純出現 true 和 false 兩種,可以單純化減少某些特別情況時的出錯機會。
例如希望'' 和 null 被視為完全相同時:

const a = ''
const b = null

a === b // false
!!a === !!b // true


測試瀏覽器對方法的支援度

var supports = !!document.querySelector && !!window.addEventListener;
if ( !supports ) return;

參考資料: pcwu's TIL Notes

全站熱搜
創作者介紹
創作者 浣熊 的頭像
浣熊

前端生涯

浣熊 發表在 痞客邦 留言(0) 人氣()