使用默认参数破坏falsey和null [英] destructuring falsey and null with default parameters

查看:111
本文介绍了使用默认参数破坏falsey和null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解如何使用默认参数来破坏false和null值。以下是我已经运行的一些例子:

I'm trying to understand how falsey 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的falsey和null值,以便我的电子邮件是一个空字符串?

Is there a shortcut I could write to destructure falsey 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 || '';

这篇关于使用默认参数破坏falsey和null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆