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

后端 未结 8 1029
不知归路
不知归路 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 03:51

    best way to check: if the param is not undefined

    function parameterTest(param) {
        if (param !== undefined)
        ...
    

    the param could be also a variable or a function name

    0 讨论(0)
  • 2020-12-13 03:52
    function parameterTest(p) {
        if ( p === undefined)
            alert('The parameter doesn\'t exist...');
        else
            alert('the parameter exists...');
    }
    
    0 讨论(0)
  • 2020-12-13 04:05

    null == undefined is true

    if (arg == null){
        // arg was not passed.
    }
    

    Code example:

    var button = document.querySelector("button");
    
    function myFunction(arg){
      if(arg == null){
        alert("argument was not passed.");
      } else {
        alert("argument " + arg + " was passed.");
      }
    }
    <button onclick="myFunction('foo');">click to fire function w arg</button>
    <br><br>
    <button onclick="myFunction();">click to fire function w/o arg</button>

    0 讨论(0)
  • 2020-12-13 04:06

    This is a very frequent pattern.

    You can test it using

    function parameterTest(bool) {
      if (bool !== undefined) {
    

    You can then call your function with one of those forms :

     parameterTest();
     parameterTest(someValue);
    

    Be careful not to make the frequent error of testing

    if (!bool) {
    

    Because you wouldn't be able to differentiate an unprovided value from false, 0 or "".

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-12-13 04:10
    function parameterTest(bool)
    {
       if(typeof bool !== 'undefined')
       {
         alert('the parameter exists...');
       }
       else
       {
         alert('The parameter doesn\'t exist...');
       }
    }
    
    0 讨论(0)
提交回复
热议问题