当前位置:首页 »“秋了秋”个人博客 » 前端编程 » JavaScript数组遍历替代switch case语句

JavaScript数组遍历替代switch case语句

作者:秋了秋 发表时间:2016年07月08日

在JavaScript中,switch case的作用想必都耳熟能详,然而当选项较多的时候,switch case要写出很长的代码,造成不美观和难以维护,比如:

switch(arrKey){
 case ".html":
   resType="text/html";
   break;
 case "":
   resType="text/html";
   break;
 case ".js":
   resType="text/javascript";
   break;
 case ".css":
   resType="text/css";
   break;
 case ".gif":
   resType="image/gif";
   break;
 case ".jpg":
   resType="image/jpeg";
   break;
 case ".png":
   resType="image/png";
   break;
 case ".ico":
   resType="image/icon";
   break;
}

如果再多一点,简直就无法阅读了,其它代码都被挤开了,然而我们可以使用数组之间的映射,这种一一对应的关系俗称字典翻译,可以完美替代switch case的写法。上面的代码可改写成如下:

var resType;
var arrKey=[".html","",".js",".css",".gif",".jpg",".png",".ico"];
var arrValue=["text/html","text/html","text/javascript","text/css","image/gif","image/jpeg","image/png","image/icon"]
arrKey.map(function(key,index){
   if(extname==key){
       resType=arrValue[index];
   }
})

或者:

var resType;
var arrKey=[".html","",".js",".css",".gif",".jpg",".png",".ico"];
var arrValue=["text/html","text/html","text/javascript","text/css","image/gif","image/jpeg","image/png","image/icon"]
arrKey.forEach(function(key,index){
   if(extname==key){
       resType=arrValue[index];
   }
})

这样明显把代码缩短了许多,而且,选项再怎么增加,代码也基本不会增加,唯有数组长度变化而已。

1
文章作者: “秋了秋”个人博客,本站鼓励原创。
转载请注明本文地址:http://netblog.cn/blog/451.html
目录: 前端编程标签: 数组循环 11350次阅读

请求播放音乐,请点击播放

登 录
点击获取验证码
还没账号?点击这里