鏈判斷運算符
編程實務中,如果讀取對象內部的某個屬性,往往需要判斷一下該對象是否存在。比如,要讀取message.body.user.firstName
,安全的寫法是寫成下面這樣。
// 錯誤的寫法 const firstName = message.body.user.firstName; // 正確的寫法 const firstName = (message && message.body && message.body.user && message.body.user.firstName) || 'default';
這樣的層層判斷非常麻煩,因此 ES2020 引入了“鏈判斷運算符”(optional chaining operator)?.
,簡化上面的寫法。
const firstName = message?.body?.user?.firstName || 'default'; const fooValue = myForm.querySelector('input[name=foo]')?.value
Null 判斷運算符
讀取對象屬性的時候,如果某個屬性的值是null
或undefined
,有時候需要為它們指定默認值。常見做法是通過||
運算符指定默認值。
const headerText = response.settings.headerText || 'Hello, world!'; const animationDuration = response.settings.animationDuration || 300; const showSplashScreen = response.settings.showSplashScreen || true;
上面的三行代碼都通過||
運算符指定默認值,但是這樣寫是錯的。開發者的原意是,只要屬性的值為null
或undefined
,默認值就會生效,但是屬性的值如果為空字符串或false
或0
,默認值也會生效。
為了避免這種情況,ES2020 引入了一個新的 Null 判斷運算符??
。它的行為類似||
,但是只有運算符左側的值為null
或undefined
時,才會返回右側的值。
const headerText = response.settings.headerText ?? 'Hello, world!'; const animationDuration = response.settings.animationDuration ?? 300; const showSplashScreen = response.settings.showSplashScreen ?? true;