JS: functions arguments default values

后端 未结 4 1085
南笙
南笙 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:31

    You would have to do it in the function body:

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

    Another way to test them for undefined or null is like this:

    function Foo(arg1 ,arg2) {
        if( arg1 == undefined )
            arg1 = 50;
    
        if( arg2 == undefined )
            arg2 = 'default';
        //...
    }
    

    Some people don't like it because it is possible to override the value of undefined since it is just a global property. As long as it isn't overridden, this would work fine. If the parameters are null or undefined, they'll be set to a default.

提交回复
热议问题