梵蒂岡之花
2023-12-14 15:10:25
我正在嘗試編寫一個滿足以下條件的函數:-從 1 數到 100, -在能被 4 整除的數字上打印“byfour”, -在能被 6 整除的數字上打印“bysix”, -在能被 4 和 6 整除的數字上打印“byfoursix”, -跳過能被 7 整除的數字, - 在數字 32 上添加“!”。這就是我所擁有的,但我想知道是否有辦法使用 switch 語句,或者有任何更優化的方式來編寫它。function maths(){ for (let i=1; i<=100; i++){ if (i === 32){ console.log (`${i}!`); } else if (i % 4 === 0 && i % 6 === 0){ console.log ("byfoursix"); } else if (i % 4 ===0) { console.log ("byfour"); } else if (i % 6 === 0) { console.log ("bysix"); } else if (i % 7 === 0){ continue; } else { console.log (i); } }}maths();任何意見或建議都非常感謝!謝謝
1 回答

繁星淼淼
TA貢獻1775條經驗 獲得超11個贊
如果您愿意,可以通過將 switch 參數設置為true使其運行來使用 switch case,盡管這不一定是更好的編寫方法。
for (let i = 1; i <= 100; i++) {
switch (true) {
case (i === 32):
console.log(`${i}!`);
break;
case (i % 4 === 0 && i % 6 === 0):
console.log('byfoursix');
break;
case (i % 4 === 0):
console.log('byfour');
break;
case (i % 6 === 0):
console.log('bysix');
break;
case (i % 7 === 0):
break;
default:
console.log(i);
}
}
添加回答
舉報
0/150
提交
取消