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

问题描述

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