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]()

在这种写法中,在表达式必定有一条成立的情况下使用。如果三条表达式都不成立,则程序不会继续执行。

原文地址:https://www.cnblogs.com/art-poet/p/12097783.html