Is there a better way to do optional function para

2018-12-31 10:08发布

This question already has an answer here:

I've always handled optional parameters in JavaScript like this:

function myFunc(requiredArg, optionalArg){
  optionalArg = optionalArg || 'defaultValue';

  // Do stuff
}

Is there a better way to do it?

Are there any cases where using || like that is going to fail?

28条回答
君临天下
2楼-- · 2018-12-31 10:56

If you're using defaults extensively, this seems much more readable:

function usageExemple(a,b,c,d){
    //defaults
    a=defaultValue(a,1);
    b=defaultValue(b,2);
    c=defaultValue(c,4);
    d=defaultValue(d,8);

    var x = a+b+c+d;
    return x;
}

Just declare this function on the global escope.

function defaultValue(variable,defaultValue){
    return(typeof variable!=='undefined')?(variable):(defaultValue);
}

Usage pattern fruit = defaultValue(fruit,'Apple');

*PS you can rename the defaultValue function to a short name, just don't use default it's a reserved word in javascript.

查看更多
伤终究还是伤i
3楼-- · 2018-12-31 10:59

You can use some different schemes for that. I've always tested for arguments.length:

function myFunc(requiredArg, optionalArg){
  optionalArg = myFunc.arguments.length<2 ? 'defaultValue' : optionalArg;

  ...

-- doing so, it can't possibly fail, but I don't know if your way has any chance of failing, just now I can't think up a scenario, where it actually would fail ...

And then Paul provided one failing scenario !-)

查看更多
柔情千种
4楼-- · 2018-12-31 11:02

Those ones are shorter than the typeof operator version.

function foo(a, b) {
    a !== undefined || (a = 'defaultA');
    if(b === undefined) b = 'defaultB';
    ...
}
查看更多
临风纵饮
5楼-- · 2018-12-31 11:03

If you need to chuck a literal NULL in, then you could have some issues. Apart from that, no, I think you're probably on the right track.

The other method some people choose is taking an assoc array of variables iterating through the argument list. It looks a bit neater but I imagine it's a little (very little) bit more process/memory intensive.

function myFunction (argArray) {
    var defaults = {
        'arg1'  :   "value 1",
        'arg2'  :   "value 2",
        'arg3'  :   "value 3",
        'arg4'  :   "value 4"
    }

    for(var i in defaults) 
        if(typeof argArray[i] == "undefined") 
               argArray[i] = defaults[i];

    // ...
}
查看更多
浅入江南
6楼-- · 2018-12-31 11:05

If you're using the Underscore library (you should, it's an awesome library):

_.defaults(optionalArg, 'defaultValue');
查看更多
十年一品温如言
7楼-- · 2018-12-31 11:06

This is what I ended up with:

function WhoLikesCake(options) {
  options = options || {};
  var defaultOptions = {
    a : options.a || "Huh?",
    b : options.b || "I don't like cake."
  }
  console.log('a: ' + defaultOptions.b + ' - b: ' + defaultOptions.b);

  // Do more stuff here ...
}

Called like this:

WhoLikesCake({ b : "I do" });
查看更多
登录 后发表回答