JS: functions arguments default values

后端 未结 4 1067
南笙
南笙 2021-01-04 21:46

In some languages you can set default values for function\'s arguments:

function Foo(arg1 = 50, arg2 = \'default\') {
    //...
}

How do yo

4条回答
  •  礼貌的吻别
    2021-01-04 22:33

    In JavaScript, anything that isn't set is given the value undefined. This means that if you want to set default values for a function, your first line needs to be a check to see if those values aren't defined:

    function Foo(arg1, arg2) {
        if (typeof(arg1) === "undefined") { arg1 = 50; }
        if (typeof(arg2) === "undefined") { arg2 = "default"; }
    }
    

    You can take a bit of a short cut if you know roughly what those values will be:

    function Foo(arg1, arg2) {
        arg1 = arg1 || 50;
        arg2 = arg2 || "default";
    }
    

    However, if those arguments are falsy, they'll be replaced. This means that if arg1 is an empty string, null, undefined, false or 0 it'll be changed to 50, so be careful if you chose to use it

提交回复
热议问题