【发布时间】: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