我们怎样来提高和优化javascript里嵌套的if
语句呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
if (color) { if (color === 'black') { printBlackBackground(); } else if (color === 'red') { printRedBackground(); } else if (color === 'blue') { printBlueBackground(); } else if (color === 'green') { printGreenBackground(); } else { printYellowBackground(); } } |
一种方法来提高嵌套的if
语句是用switch
语句。虽然它不那么啰嗦而且排列整齐,但是并不建议使用它
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
switch(color) { case 'black': printBlackBackground(); break; case 'red': printRedBackground(); break; case 'blue': printBlueBackground(); break; case 'green': printGreenBackground(); break; default: printYellowBackground(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
switch(true) { case (typeof color === 'string' && color === 'black'): printBlackBackground(); break; case (typeof color === 'string' && color === 'red'): printRedBackground(); break; case (typeof color === 'string' && color === 'blue'): printBlueBackground(); break; case (typeof color === 'string' && color === 'green'): printGreenBackground(); break; case (typeof color === 'string' && color === 'yellow'): printYellowBackground(); break; } |
但是我们应该时刻注意避免太多判断在一个条件里,尽量少的使用switch
,考虑最有效率的方法:借助object
。
1 2 3 4 5 6 7 8 9 10 11 12 |
var colorObj = { 'black': printBlackBackground, 'red': printRedBackground, 'blue': printBlueBackground, 'green': printGreenBackground, 'yellow': printYellowBackground }; if (color in colorObj) { colorObj[color](); } |