标签:
在项目过程中经常遇到需要做条件判断。在判断条件比较多的情况下我们一般使用的方法是如下:
1 if (color) { 2 if (color === ‘black‘) { 3 console.log(color); 4 } else if (color === ‘red‘) { 5 console.log(color); 6 } else if (color === ‘blue‘) { 7 console.log(color); 8 } else if (color === ‘green‘) { 9 console.log(color); 10 } else { 11 console.log(color); 12 } 13 }
机智点的可以使用switch
1 switch(color) { 2 case ‘black‘: 3 console.log(color); 4 break; 5 case ‘red‘: 6 console.log(color); 7 break; 8 case ‘blue‘: 9 console.log(color); 10 break; 11 case ‘green‘: 12 console.log(color); 13 break; 14 default: 15 console.log(color); 16 }
尽管这样能解决并且更有序,但不推荐这样做,因为会给debug增加麻烦。而且语句需要不断的做判断。
尽可能 的与避免使用switch那么就需要一个高效的方法,那就是通过一个Object;
1 var colorObj = { 2 ‘black‘: console.log(color), 3 ‘red‘: console.log(color), 4 ‘blue‘: console.log(color), 5 ‘green‘: console.log(color), 6 ‘yellow‘: console.log(color), 7 }; 8 9 if (color && colorObj.hasOwnProperty(color)) { 10 colorObj[color](); 11 }
标签:
原文地址:http://www.cnblogs.com/liuzejin/p/5736133.html