How to test if a parameter is provided to a function?

后端 未结 8 1039
不知归路
不知归路 2020-12-13 03:45

I was wondering, can you create a function with an optional parameter.

Example:

function parameterTest(test)
{
   if exists(test)
   {
     alert(\'t         


        
8条回答
  •  再見小時候
    2020-12-13 04:08

    I know this is old, but this is my preferred way to check, and assign default values to functions:

    function testParamFunction(param1, param2) {
        param1 = typeof param1 === 'undefined' ? null : param1;
        param2 = typeof param2 === 'undefined' ? 'default' : param2;
    
        // exit if the required parameter is not passed
        if (param1 === null) {
            console.error('Required parameter was not passed');
            return;
        }
    
        // param2 is not mandatory and is assigned a default value so 
        // things continue as long as param1 has a value
    }
    

提交回复
热议问题