前言:
现在姐妹们对“js的if语句”大约比较着重,兄弟们都需要剖析一些“js的if语句”的相关文章。那么小编也在网上网罗了一些关于“js的if语句””的相关知识,希望小伙伴们能喜欢,我们一起来学习一下吧!我们怎样来提高和优化javascript里嵌套的if语句呢?
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();}
如果可以重构的话,我们可以试着简化函数。比如不需要为每个颜色写一个函数,而是将颜色作为函数的参数。
function printBackground(color) { if (!color || typeof color !== 'string') { return; // Invalid color, return immediately }}
但是如果不能重构的话,我们必须避免过多的条件检查,避免过多使用switch。我们必须考虑最有效率的方法,使用object。
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。
var colorObj = { 'black': printBlackBackground, 'red': printRedBackground, 'blue': printBlueBackground, 'green': printGreenBackground, 'yellow': printYellowBackground};if (color in colorObj) { colorObj[color]();}
各种技巧来自于网上学习和工作积累