用默认参数解构false和null

destructuring falsy and null with default parameters

本文关键字:false null 默认 参数      更新时间:2023-09-26

我试图理解如何用默认参数解构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?!

是否有一个快捷方式,我可以写解构假和null值#3和#4,使我的电子邮件是一个空字符串?

只有undefined会导致默认初始化器在解构和函数参数目标中运行。如果您想退回到所有假值的默认值,请使用旧的||操作符:

const email = person.email || '';

或者以可变变量为目标,然后使用逻辑或赋值:

let { email } = person;
email ||= '';