?. 鏈式判斷運算符
<==>
a?.[++x] 相當於 a == null?undefined : a[++x] (a如果為undefined或者null,則返回undefined) undefined == null
左側的對象是否為null
或undefined
。如果是的,就不再往下運算,而是返回undefined
。
鏈判斷運算符?.
有三種寫法。
obj?.prop
// 對象屬性是否存在obj?.[expr]
// 同上func?.(...args)
// 函數或對象方法是否存在
Null 判斷運算符
const headerText = response.settings.headerText || 'Hello, world!';
const animationDuration = response.settings.animationDuration || 300;
const showSplashScreen = response.settings.showSplashScreen || true;
短路機制,如果左側的值為空串、0、false、undefined、null,最終結果為右側的值
要想實現,當且僅當左側的值為undefined或者null時,最終結果為右側的值,就需要使用到Null 判斷運算符
const headerText = response.settings.headerText ?? 'Hello, world!';
const animationDuration = response.settings.animationDuration ?? 300;
const showSplashScreen = response.settings.showSplashScreen ?? true;