js if 條件語句優化寫法


if...else if...else...寫法

const condition = 2

if(condition == 1) {
       document.write(1)
}else if(condition == 2){
       document.write(2)
}else{
       document.write(3)
}

優化寫法:

const condition = 2
let obj = {
  '1' : () => { document.write(1) },
  '2' : () => { document.write(2) },
  '3' : () => { document.write(3) },
}

obj[condition]()

在這種寫法中,在表達式必定有一條成立的情況下使用。如果三條表達式都不成立,則程序不會繼續執行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM