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

后端 未结 8 1030
不知归路
不知归路 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:10

    init default values if not exists:

    function loadDialog(fn, f, local, anim) {
      switch (arguments.length) {  
        case 1: f=null;
        case 2: local=false;
        case 3: anim=false;
      }
      ...
    }
    
    0 讨论(0)
  • 2020-12-13 04:13

    In JavaScript, if you neglect to give a parameter it will default to undefined.

    You could try it out for yourself easily enough, either in your browser console or using JSFiddle.

    You can check for the existance of the parameter, as you say, and that way write a function that can use a parameter or not. However, JavaScript Garden (a great resource) recommends staying away from typeof in most other cases, as its output is just about useless (check out the table of results of typeof).

    0 讨论(0)
提交回复
热议问题