??(nullish 合併運算子) - daniel-qa/Vue GitHub Wiki
??(nullish 合併運算子)
運算子 | 作用 | 範例 |
---|---|---|
?. |
安全取用物件屬性,避免因為 null 或 undefined 拋錯 |
obj?.prop |
?? |
當左邊是 null 或 undefined 時,回傳右邊的值(作為預設值) |
value ?? defaultValue |
?.(optional chaining)避免因為 null 或 undefined 存取屬性時,造成程式崩潰的超棒語法。
?. 就是 JavaScript 的安全繩索,讓你放心攀爬物件屬性樹,不怕摔跤!
{{ item?.type === 2 ? 'ID' : '学校' }}
裡面用到了 optional chaining (?.),意義就是:
如果 item 是 null 或 undefined,整個 item?.type 會直接變成 undefined,不會噴錯。
接著 undefined === 2 是 false,所以會走到 : '学校' 這邊顯示。
簡單說,就是 不會因為 item 或 item.type 不存在導致錯誤,而且能正常顯示預設值「学校」。
stats?.scCnt ?? 0 ==> 這個可以防 undefined 報錯,加上預設值
語句 | 說明 |
---|---|
stats?.scCnt ?? 0 |
使用 optional chaining(?. ):如果 stats 是 null 或 undefined ,整個表達式會變成 undefined ,再用 ?? 0 補上預設值。 |
item.tchCnt ?? 0 |
沒用 ?. :如果 item 是 undefined ,這行會直接拋出錯誤(TypeError: Cannot read properties of undefined )!因為它嘗試存取 undefined.tchCnt 。 |