使用默认参数解构 falsy 和 null [英] destructuring falsy and null with default parameters
本文介绍了使用默认参数解构 falsy 和 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图了解如何使用默认参数解构虚假和空值.以下是我运行过的一些示例:
I'm trying to understand how falsy and null values are destructured with default parameters. Here are some examples I've ran:
// #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 的虚假和空值,以便我的电子邮件是空字符串?
Is there a shortcut I could write to destructure falsy and null values for #3 and #4 so that my email is an empty string?
推荐答案
只有 undefined
会导致默认初始化程序运行.如果您想为所有虚假值回退到默认值,请使用旧的 ||
运算符:
Only undefined
will cause the default initialiser to run. If you want to fall back to your default for all falsy values, use the good old ||
operator:
const email = person.email || '';
这篇关于使用默认参数解构 falsy 和 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文