开发者

Pass comma-separated arguments to js function

开发者 https://www.devze.com 2023-01-29 23:13 出处:网络
I have the following function: function calculateAspect(options){ def = { orgw: 0, orgh: 0, tarw: 0, tarh: 0

I have the following function:

function calculateAspect(options){
    def = {
        orgw: 0,
        orgh: 0,
        tarw: 0,
        tarh: 0
    };
    o = $.extend(def,options);
    console.log(o);


};    
calculateAspect({orgw:640});

And i want to be able to pass it values like following:

calculatedAspect(640,480,320)

or

calculateAspect(200)

This may not seem logical, given the function. But i am just curious how to pull it of开发者_运维问答f.


You can use arguments that contains all passed arguments:

function calculateAspect(options){
    var argNames = ["orgw","orgh","tarw","tarh"];
    def = {
        orgw: 0,
        orgh: 0,
        tarw: 0,
        tarh: 0
    };
    for (var i=0, n=Math.min(arguments.length, 4); i<n; i++) {
        def[argNames[i]] = arguments[i];
    }
    console.log(o);
}


You'd have to make up your own convention for what the parameters should mean, but you could do something like this:

function calculateAspect(orgw, orgh, tarw, tarh) {
  var def = { /* ... */ };
  if (arguments.length === 1 && (typeof orgw) === "object") {
    var o = $.extend(def, orgw);
    // ... normal code ...
  }
  else {
    calculateAspect({orgw: orgw, orgh: orgh, tarw: tarw, tarh: tarh});
  }
}

maybe.

0

精彩评论

暂无评论...
验证码 换一张
取 消