【问题标题】:How to reduce multiple if statements complexity如何降低多个 if 语句的复杂性
【发布时间】:2021-09-08 03:46:42
【问题描述】:

我觉得 5 个 if 语句可以用一行代码或更少行来完成。我正在考虑使用forEach 方法,但我无法正确地改进它。

var previous_stays = 12,
    booking_agency_id = null,
    reservation_spend = 375.95,
    room_spend = [12.23,2.35,null,17.99],
    reservation_nights = 4,
    gold_tier = 0;

while (gold_tier == 0) {
 a = (previous_stays >= 5);
 b = !booking_agency_id;
 c = reservation_spend;
 d = reservation_nights;

 if (room_spend.length > 0) {
     c = c + room_spend[0];
     if (room_spend.length > 1) {
         c = c + room_spend[1];
         if (room_spend.length > 2) {
             c = c + room_spend[2];
             if (room_spend.length > 3) {
                 c = c + room_spend[3];
                 if (room_spend.length > 4) {
                     c = c + room_spend[4];
                     if (room_spend.length > 5) {
                         c = c + room_spend[5];
                     }
                 }
             }
         }
     }
 }

 if (!(((c/d) > 250) && a && b)) {
   break;
 }

 gold_tier = 1;
}

【问题讨论】:

  • c = room_spend[room_spend.length]
  • 看起来您只是将room_spend 的总和添加到c 所以它只是:c = room_spend.reduce((a, e) => a + e, reservation_spend)
  • while 循环的意义何在?它只运行一次。
  • 解释这对你有好处
  • @marzelin 有效!但是 .reduce 到底在做什么呢?

标签: javascript arrays loops if-statement foreach


【解决方案1】:

嗯,我认为问题是“什么是 0、1、2、3...”,您要与之比较?假设您将其作为称为“类别”的参数接收。所以所有操作都可以简化为:

if(room_spend.length > category){
     c = c + room_spend[category]
}

所以问题是赋予这个“类别”一些意义。

【讨论】:

    【解决方案2】:

    这是一种方法,设置您要检查的最大长度并向后循环。

    let l = 6; // (max length +1)
    while(l-->0) if (room.spend.length>l) { c = c+room_spend[l]; break;}
    

    let room={spend:"1234"}
    
    let l = 6
    while(l-->0) if (room.spend.length>l) { console.log('c = c + room_spend['+l+']'); break;}
    
     

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-14
      相关资源
      最近更新 更多