簡體   English   中英

使用默認參數解析falsey和null

[英]destructuring falsey and null with default parameters

我試圖了解如何使用默認參數對false值和null值進行解構。 以下是我跑過的一些例子:

// #1
const person = { email: 'a@example.com' }
const { email = '' } = person
// email is 'a@example.com'

// #2
const person = { email: '' }
const { email = '' } = person
// email is ''

// #3
const person = { email: false }
const { email = '' } = person
// email is boolean false.  why?!

// #4
const person = { email: null }
const { email = '' } = person
// email is null.  why?!

有沒有我可以編寫的快捷方式來構造#3和#4的falsey和null值,以便我的電子郵件是空字符串?

只有undefined才會導致默認初始化程序運行。 如果你想回到所有假值的默認值,請使用舊的|| 運營商:

const email = person.email || '';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM