您的位置:首页 > Web前端 > JavaScript

js优化嵌套的条件语句

2016-08-24 15:09 423 查看
if (color) {
if (color === 'black') {
printBlackBackground();
} else if (color === 'red') {
printRedBackground();
} else if (color === 'blue') {
printBlueBackground();
} else if (color === 'green') {
printGreenBackground();
} else {
printYellowBackground();
}
}
一种方法来提高嵌套的
if
语句是用[code]switch
语句。虽然它不那么啰嗦而且排列整齐,但是并不建议使用它,因为这对于调试错误很困难。[/code]
switch(color) {case 'black':printBlackBackground();break;case 'red':printRedBackground();break;case 'blue':printBlueBackground();break;case 'green':printGreenBackground();break;default:printYellowBackground();}
但是我们应该时刻注意避免太多判断在一个条件里,尽量少的使用[code]switch
,考虑最有效率的方法:借助
object
。[/code]
var colorObj = {'black': printBlackBackground,'red': printRedBackground,'blue': printBlueBackground,'green': printGreenBackground,'yellow': printYellowBackground};if (color in colorObj) {colorObj[color]();}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js 条件语句