【问题标题】:What can I do to address diminishing logical operators?我能做些什么来解决递减的逻辑运算符?
【发布时间】:2019-07-09 22:48:29
【问题描述】:

我有一个类似的对象

{
  a: 'string1',
  b: 'string2',
  c: 'string3',
  d: 'string4',
  e: 'string5',
  f: 'string6',
  g: 'string7',
  h: 'string8',
  i: 'string9'
}

我需要做以下逻辑

if (a && (b || c || d || e || f || g || h || i)) dothis1()
if (b && (c || d || e || f || g || h || i)) dothis2()
if (c && (d || e || f || g || h || i)) dothis3()
if (d && (e || f || g || h || i)) dothis4()
if (e && (f || g || h || i)) dothis5()
if (f && (g || h || i)) dothis6()
if (g && (h || i)) dothis6()
if (h && i) dothis7()

我已经尝试过上述方法,但必须有一种更简单的方法来做到这一点,这让我大吃一惊。谁有更好的选择?

【问题讨论】:

  • 将所有值放入一个数组中,将要调用的函数放入第二个并行数组中,并尝试编写一些基于数组的逻辑。如果您遇到困难,展示是您的尝试,我们可以为您提供进一步的建议。
  • 那我还是老样子吧?如果我将所有值放入一个数组并尝试array.includes,它仍将是if (a && (array.includes(string2) || array.includes(string3)... 等。我认为这不是我使用什么的问题,而是我不明白怎么做,因为它有点时髦。您建议我研究哪种数组方法?

标签: javascript object logical-operators


【解决方案1】:

使用数组很容易做到这一点。函数编号有点棘手 - 尝试将所有函数也放入一个数组中。并使用some 使循环短路:

const funcArr = [dothis1, dothis2, dothis3, dothis4, dothis5, dothis6, dothis7];

Object.entries(obj).some((e, i, a) => {
  if (i + 2 == a.length && e && a[i + 1]) return (funcArr[funcArr.length - 1](), 1);
  if (e && a.slice(i + 1).some(e => e)) return (funcArr[i](), 1);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-26
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 2010-10-29
    • 2016-03-11
    相关资源
    最近更新 更多