ES6 語句判斷簡寫


鏈判斷運算符

編程實務中,如果讀取對象內部的某個屬性,往往需要判斷一下該對象是否存在。比如,要讀取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 判斷運算符

讀取對象屬性的時候,如果某個屬性的值是nullundefined,有時候需要為它們指定默認值。常見做法是通過||運算符指定默認值。

const headerText = response.settings.headerText || 'Hello, world!';
const animationDuration = response.settings.animationDuration || 300;
const showSplashScreen = response.settings.showSplashScreen || true;

  上面的三行代碼都通過||運算符指定默認值,但是這樣寫是錯的。開發者的原意是,只要屬性的值為nullundefined,默認值就會生效,但是屬性的值如果為空字符串或false0,默認值也會生效。

為了避免這種情況,ES2020 引入了一個新的 Null 判斷運算符??。它的行為類似||,但是只有運算符左側的值為nullundefined時,才會返回右側的值。

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