簡體   English   中英

我可以在以下任何問題中使用“switch”語句嗎? 或者'else if'是go的正確方法嗎?

[英]can I use the 'switch' statement in any of the questions below? or is the 'else if' the right way to go?

我正在嘗試編寫滿足以下條件的 function:

- 從 1 到 100 計數,-on 可被 4 整除的數字打印“byfour”,-on 可被 6 整除的數字打印“bysix”,-on 可被 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();

任何意見或建議都非常感謝! 謝謝

如果您願意,可以通過將 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);
      }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM