我正在尝试理解如何使用默认参数来解构falsy和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的错误和空值,这样我的电子邮件就是一个空字符串?
发布于 2016-09-16 08:04:50
只有undefined会导致运行默认的初始化程序。如果您想回退到所有错误值的默认值,请使用良好的旧||运算符:
const email = person.email || '';https://stackoverflow.com/questions/39522014
复制相似问题