【问题标题】:How to shorten multiple if statements (not if else)如何缩短多个 if 语句(不是 if else)
【发布时间】:2022-06-15 21:44:58
【问题描述】:

我有一个数组,我想在其中有条件地推送一些值。有没有更简洁的方法(下面的代码)?

const pushedValues = []; 
if (someArray[0].value) {
    pushedValues.push(x);
}
if (someArray[1].value) {
    pushedValues.push(y);
}
if (someArray[2].value) {
    pushedValues.push(z);
}
...

【问题讨论】:

  • 如果someArray和x、y、z中的值彼此没有任何联系。不,你不能。如果您可以借助someArray 中的相应值(或索引)确定x y 和y,则可以使用循环。
  • 使用循环! (并将x、y 和z 也存储在一个数组中)

标签: javascript typescript


【解决方案1】:

您可以将值 x, y, z 放入一个数组中,然后使用索引循环这些值。

const pushedValues = []; 
[x, y, z].forEach((val, i)=>{
    if(someArray[i].value) pushedValues.push(val);
});

【讨论】:

    【解决方案2】:

    你可以像这样使用 forEach

    const pushedValues = []; 
    const data = [x, y, z]
    someArray.forEach((v, i) => {
     v.value && pushedValues.push(data[i])
    })
    

    【讨论】:

      【解决方案3】:

      您正在使用someArray 数组。您必须首先检查迭代控件(for 或 while)中的值,然后使用switch-case 构造。

      再见 M

      【讨论】:

        猜你喜欢
        • 2012-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多