【问题标题】:How do I return the number value of an if statement if certain conditions are met?如果满足某些条件,如何返回 if 语句的数值?
【发布时间】:2021-12-23 02:58:32
【问题描述】:

我正在研究一个函数,如果数组的某些属性为真,则返回这些条件为真的数量。

例如

if (a > b || a < c || d == e || f == e)
{
  return "number of condition that are met";
}

【问题讨论】:

  • 你能证明任何尝试自己解决这个问题吗?
  • 我们不是您的个人代码编写服务 - 向我们展示您尝试过什么/编写了哪些代码(作为minimal reproducible example)以尝试满足此要求,以及在哪里特别是你被卡住了。 How to Ask

标签: javascript return-value


【解决方案1】:

将条件存储在数组中

const conditions = [
   (a,b,c,d,e,f) => a>b,
   (a,b,c,d,e,f) => a<c,
   (a,b,c,d,e,f) => d==e,
   (a,b,c,d,e,f) => f==e,
];

现在,您可以使用filter 找出有多少是真的

const howManyTrues = conditions.filter(cond => cond(a,b,c,d,e,f) )
if(howManyTrue > 0){
    return howManyTrue;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    • 2017-07-29
    相关资源
    最近更新 更多