空检查变形变量 [英] Null check for destructured variables

查看:59
本文介绍了空检查变形变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码从一个对象创建三个常量.

I have the below code to create three constant from an object.

const {standing_bid_amt, min_increment, starting_price} = props.auction.auction;

但是,如果Auction是一个空对象,则上述常量之上的问题将是不确定的.为了解决这个问题,我将代码更改为

But the issue here is above constants will be undefined if auction is an empty object. To fix this, I have changed the code to

const {standing_bid_amt, min_increment, starting_price} = props.auction.auction ? props.auction.auction : {standing_bid_amt: null, min_increment:null, starting_price:null};

尽管可以,但是我觉得这不是对常量进行空值检查的最佳方法.请让我知道是否有更好的方法可以使用null检查创建常量.

Although it works, I feel maybe this is not the best way to do a null check for the constants. Please do let me know if there is any better way to create the constants with null check.

推荐答案

而不是使用条件运算符,而是与{}交替使用,并将默认值(null)分配给已分解的变量(这样, =的一侧为空对象,null放入变量中):

Instead of using the conditional operator, alternate with {}, and assign default values (null) to the destructured variables (so that, when the right-hand side of the = evaluates to the empty object, null gets put into the variables):

const {
  standing_bid_amt = null,
  min_increment = null,
  starting_price = null
} = props.auction.auction || {};

const doSomething = (props) => {
  const {
    standing_bid_amt = null,
    min_increment = null,
    starting_price = null
  } = props.auction.auction || {};
  console.log(min_increment);
};

doSomething({ auction: {auction: null }});
doSomething({ auction: {auction: {
  standing_bid_amt: 50,
  min_increment: 50,
  starting_price: 50
}}});

这篇关于空检查变形变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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