将多个if语句压缩为一个for和一个if
有没有办法将这四个 if 语句压缩成一个 for 循环和一个 if 条件?有人告诉我有一种方法,但我只能想到多个 else if 语句。
function New() {
if (foodInOven == true) {
timeOfCooking += 1;
}
if (timeOfCooking == 10) {
console.log("cooked pasta");
} else if (timeOfCooking == 15) {
console.log("burning pasta!");
} else if (timeOfCooking == 20) {
console.log("pasta burnt!!");
}
}
回答
一种选择是查找您的时间,如果有值,则将其记录到控制台。
const cookingLookup = {
10: "cooked pasta",
15: "burning pasta!",
20: "pasta burnt!!"
}
function New() {
if (foodInOven == true) {
timeOfCooking += 1;
}
if (cookingLookup[timeOfCooking]) {
console.log(cookingLookup[timeOfCooking]);
}
}