Pass comma-separated arguments to js function
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.
精彩评论