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]()
在這種寫法中,在表達式必定有一條成立的情況下使用。如果三條表達式都不成立,則程序不會繼續執行。