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