【发布时间】:2017-01-24 02:57:59
【问题描述】:
我试图了解如何使用默认参数解构虚假和空值。以下是我运行的一些示例:
// #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 的假值和空值,以便我的电子邮件是一个空字符串?
【问题讨论】:
-
这将是一个真正的“为什么?!”如果它默认每个虚假值。该问题可能是 XY 问题的一部分,如果
person是任意输入,则应首先根据您的规则对其进行调节和验证。