将if else语句转换为带数组的函数



如何用数组代替变量(bill, tip1, tip2)创建函数if else语句

const bill = 320
const tip1 = 50
const tip2 = 300
if (bill < tip1) {
console.log(`bill is ${bill} with 10% tip so the total will be ${bill * 0.10 + bill}`);
} else if (bill < tip2) {
console.log(`bill is ${bill} with 15% tip so the total will be ${bill * 0.15 + bill}`);
} else {
console.log(`bill is ${bill} with 20% tip so the total will be ${bill * 0.20 + bill}`);
}

你的意思是?

function chck(bill, tips, discounts){
let sm = false;
for(let i = 0; i < tips.length; i++){
if(bill < tips[i]){
console.log(`bill is ${bill} with ${discounts[i]} tip so the total will be ${bill * discounts[i] + bill}`);
sm = true;
break;
}
}
if(sm == false){
console.log(`bill is ${bill} with 40% tip so the total will be ${bill * 0.20 + bill}`);
}
}
let = bill = 1000;
let tips = [50,300,500,600,800,900];
let discounts = [0.10,0.15,0.20,0.25,0.30,0.35];
chck(bill, tips, discounts);
bill = 320;
chck(bill, tips, discounts);
bill = 290;
chck(bill, tips, discounts);
bill = 30;
chck(bill, tips, discounts);

最新更新