【代码分享】根据类型智能提取参数

如果你是个Javascript程序员,那一定经常写下面的代码:

function funcA(url, params, callback, option){
    if(arguments.length == 2){
        //funcA(url, callback);
        if(typeof params == 'function'){
            callback = params;
            params = {};
        }else{
            //funcA(url, params);
            //......
        }
    }else {
        //......
    }
}

当参数变化形式比较少的时候还没问题,当你的方法想对多种传参形式进行容错时,一堆的if else判断就变得很难看了。这时不妨尝试下这个 getArguments 方法。more

var toString = Object.prototype.toString;

var is = function(obj){
    var type = toString.apply(obj);
    type = type.substring(8, type.length - 1);
    return type;
}

var getArguments = function(argus, type1, type2, type3 /*...*/){
    var srcTypes = [];
    var targetTypes = Array.prototype.slice.call(arguments, 1);
    var result = [];
    for(var i = 0, len = argus.length; i < len; i++) {
        srcTypes.push(is(argus[i]));
    }
    for(var m = 0, n = 0, len = targetTypes.length; n < len; ){
        if(srcTypes[m] === targetTypes[n]){
            result.push(argus[m]);
            m++, n++;
        }else{
            result.push(null);
            n++;
        }
    }
    return result;
}

使用方法如下:

function funcB(name, params, callback, option){
    var argus = getArguments(arguments, 'String', 'Object', 'Function', 'Object');
    name = argus[0], params = argus[1] || {}, callback = argus[2], option = argus[3] || {};
    console.log(argus);
}

运行结果如下:

funcB('a',function(){})
//console: ["a", null, function, null]
funcB('a',function(){}, {o:1})
//console: ["a", null, function, Object]
funcB('a',{p:1})
//console: ["a", Object, null, null]
funcB({p:1})
//console: [null, Object, null, null]
funcB(function(){})
//console: [null, null, function, null]

怎么样,是不是简单很多咧?^_^