es6 ?.與??


?.  鏈式判斷運算符

<==>

a?.[++x]   相當於   a == null?undefined : a[++x]  (a如果為undefined或者null,則返回undefined)  undefined == null

左側的對象是否為nullundefined。如果是的,就不再往下運算,而是返回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;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM