我是
靠谱客的博主
闪闪汉堡,最近开发中收集的这篇文章主要介绍
js优化嵌套的条件语句,觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
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
语句。虽然它不那么啰嗦而且排列整齐,但是并不建议使用它,因为这对于调试错误很困难。
switch(color) {
case 'black':
printBlackBackground();
break;
case 'red':
printRedBackground();
break;
case 'blue':
printBlueBackground();
break;
case 'green':
printGreenBackground();
break;
default:
printYellowBackground();
}
但是我们应该时刻注意避免太多判断在一个条件里,尽量少的使用switch
,考虑最有效率的方法:借助object
。
var colorObj = {
'black': printBlackBackground,
'red': printRedBackground,
'blue': printBlueBackground,
'green': printGreenBackground,
'yellow': printYellowBackground
};
if (color in colorObj) {
colorObj[color]();
}
最后
以上就是闪闪汉堡为你收集整理的js优化嵌套的条件语句的全部内容,希望文章能够帮你解决js优化嵌套的条件语句所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复