如何解决如何减少多个 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;}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。