js 谢绝 if ... else

先看通例的前提语句的写法:

    function getInitData(columnType){
        if(columnType == "baiduZhidaoNum"){
            return {searchText:"", href:""};
        }else if(columnType == "weBo"){
            return {weiboType:"xinlangWeibo",weiboUrl:""};
        }else if(columnType == "APPDownload"){
            return {downLoadType:"templateSetting"};
        }else if(columnType == "contactPhone"){
            return {phoneArray:""};
        }else if(columnType == "inlineMap"){
            return {address:"", latitude:"", longitude:""};
        }else if(columnType == "weStore"){
            return {weiStoreType: "taobaoStore", storeWebAddress:""};
        }else if(columnType == "weRecruit"){
            return {jobType:"weijob_zhaopinUrl", content:"", weijobUrl:""};
        }
    }

谢绝if else以后大概是如许:

/*
    这里使用了ES6的Arrow Function,
    var fun = ()=>({searchText:"", href:""})
    等价于:
   var fun = function(){
        return {searchText:"", href:""}
    }
    
    或:
    var fun = (arg1, arg2)=>({searchText: arg1, href:arg2})
    等价于:
   var fun = function(arg1, arg2){
        return {searchText: arg1, href:arg2}
    }
*/
function getInitJumpPage(columnType){
        return {
                "baiduZhidaoNum" : ()=>({searchText:"", href:""}),
                "weBo" : ()=>({weiboType:"xinlangWeibo",weiboUrl:""}),
                "APPDownload" : ()=>({downLoadType:"templateSetting"}),
                "contactPhone" : ()=>({phoneArray:""}),
                "inlineMap" : ()=>({address:"", latitude:"", longitude:""}),
                "weStore" : ()=>({weiStoreType: "taobaoStore", storeWebAddress:""}),
                "weRecruit" : ()=>({jobType:"weijob_zhaopinUrl", content:"", weijobUrl:""}),
            }[columnType]();
    原文作者:idgq
    原文地址: https://segmentfault.com/a/1190000006047786
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞