【问题标题】:check if at least one of multiple object properties is true [duplicate]检查多个对象属性中的至少一个是否为真[重复]
【发布时间】:2019-04-10 09:41:23
【问题描述】:

当涉及到 if 语句时,可以重构此代码

(这只是一个例子,并不指“真实”的代码)

if(person === 'customer' || person === 'employee' || person === 'other')

if(person === ('customer' || 'employee' || 'other'))

目前我有一个名为 state 的对象,其中包含 3 个布尔属性。如果至少一个属性返回true,我想显示一个叠加层。我目前的解决方案是这样的

showOverlay: state => state.isNavigating || state.isHttpRequesting || state.isProcessing

我在问是否有办法清理它。伪代码将是

showOverlay: state => (isNavigating || isHttpRequesting || isProcessing) of state

我知道它没有什么大收获,但它会删除所有 state. ... 部分。

【问题讨论】:

  • it is possible to refactor this code 不,不是,它们是两个不同的结果
  • ['customer', 'employee', 'other'].includes(person) 但这与您的其他代码完全不同
  • @CertainPerformance - OP 声明第二段代码对第一段的有效重构!
  • state => { with(state) { return isNavigating || isHttpRequesting || isProcessing; } } ... 开个玩笑 :)
  • 很抱歉,premature optimization is the root of all evil 是我目前最大的敌人 .. :(

标签: javascript


【解决方案1】:

使用属性名数组,检查其中some是否为真:

showOverlay: state => ['isNavigating', 'isHttpRequesting', 'isProcesing'].some(prop => state[prop]);

也许它更干燥,这可以说是好的,但是当只有 3 个 IMO 属性时,它的可读性会有点差,这可以说是不好的。

【讨论】:

  • 谢谢,性能怎么样?创建一个数组并循环遍历它是不是很糟糕?
  • 在现代计算机上,性能几乎从来不用担心,除非您已经运行了性能测试并确定了导致瓶颈的一段代码——不用担心。默认情况下,干净、可读的代码会更好。 (不过,这干净易读吗?由你决定。也许如果有 4 个以上的属性,我肯定会更喜欢数组,但我不确定是否只有 3 个)
猜你喜欢
  • 2023-03-19
  • 2017-10-06
  • 1970-01-01
  • 2023-03-27
  • 2015-09-22
  • 2021-11-14
  • 1970-01-01
  • 2011-03-05
  • 1970-01-01
相关资源
最近更新 更多