关于优化的方式
摘自:http://www.cnblogs.com/lranye/archive/2013/06/08/3127013.html
3、当进行多个条件判段时
给一个例子:每种颜色对应一个值,比如"white","red","green","yellow","gray","blue" 分别对应的值为0,1,2,3,4,5
1) 问题一:根据值获取颜色
实现方式一
function getColorByVal(val) { var color = "" ; if (val == 0){ color = "white" ; } else if (val == 1) { color = "red" ; } else if (val == 2) { color = "green" ; } else if (val == 3) { color = "yellow" ; } else if (val == 4) { color = "gray" ; } else if (val == 5) { color = "blue" ; } return color; } |
实现方式二
function getColorByVal(val) { var color; switch (val) { case 0: color = "white"; case 1: color = "red"; break; case 2: color = "green"; break; case 3: color = "yellow"; break; case 4: color = "gray"; break; case 5: color = "blue"; break; } return color; }
实现方式三
function getColorByVal(val) { return [ "white" , "red" , "green" , "yellow" , "gray" , "blue" ][val]; } |
调用: var color=getColorByVal(2);
方式一和方式二相比没什么差别,但方式二稍微好一点,而方式三则是让人眼前一亮,短小精悍就完成了功能。不过有的人会说颜色的值刚好是数组
再有:
function getValByColor(color){ return {"white":0,"red":1,"green":2,"yellow":3,"gray":4,"blue":5}[color]; }
调用: var val=getValByColor("red");