繁体   English   中英

如何减少多个 if 语句的复杂性

[英]How to reduce multiple if statements complexity

我觉得 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;
}

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

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

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

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

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;}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM