gpt4 book ai didi

javascript - 简化包含潜在 undefined variable 的 bool 表达式

转载 作者:行者123 更新时间:2023-11-30 19:45:25 25 4
gpt4 key购买 nike

我有一个这样定义的 bool 表达式:

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

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

最佳答案

既然听起来您已经在使用 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;

关于javascript - 简化包含潜在 undefined variable 的 bool 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54992017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com