使用默认参数解析falsey和null

Kev*_*vin 16 javascript ecmascript-6

我试图了解如何使用默认参数对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?!
Run Code Online (Sandbox Code Playgroud)

有没有我可以编写的快捷方式来构造#3和#4的falsey和null值,以便我的电子邮件是空字符串?

Ber*_*rgi 29

只会undefined导致默认初始化程序运行.如果要回退到所有假值的默认值,请使用旧的||运算符:

const email = person.email || '';
Run Code Online (Sandbox Code Playgroud)

  • 如果是这样的情况, `const person = { name:null, email: null }; const { name = '', email = '' } = person` 有什么简单的解决方案吗? (3认同)
  • @srikanthsharma当然,就像使用解构时一样 (2认同)
  • @foxiris如果你想要很多变量,你需要编写很多代码。没有办法解决这个问题。如果适用,请使用一般处理属性的循环。顺便说一句,换行并不重要。 (2认同)