简化包含潜在未定义变量的布尔表达式

问题描述 投票:1回答:1

我有一个布尔表达式定义如下:

const actif =
  this.props.configuration &&
  this.props.configuration.puissance &&
  this.props.configuration.puissance > 0

取决于组件,this.props。或许没有configurationconfiguration可能或没有puissance。这就是为什么我需要做所有这些验证。

使用{ has } from 'lodash',我已经能够简化一下了:

const actif =
      has(this.props.configuration, 'puissance') &&
      this.props.configuration.puissance > 0

但那也不是很令人满意。

我尝试了别的东西。我知道JS允许你做这样的事情:

(undefined || 4) === 4

这是真的。不幸,

(this.props.configuration.puissance || undefined ) > 0 

仍然给我Cannot read property 'puissance' of undefined

有没有一种简单的方法来进行这种比较而无需检查整个对象树? (如果任何步骤未定义,则停止在树中继续前进?)

javascript comparison-operators
1个回答
1
投票

既然听起来你已经在使用lodash了,那么使用lodash's _.get() function怎么样?

const actif = _.get(this.props, "configuration.puissance", 0) > 0;

a proposal for an optional chaining property in JavaScript,但它尚未成为语言。当它/如果它,你可以做这样的事情:

const actif = this.props?.configuration?.puissance || 0 > 0;
© www.soinside.com 2019 - 2024. All rights reserved.