【问题标题】:How to test if a parameter is provided to a function?如何测试是否为函数提供了参数?
【发布时间】:2012-10-22 20:50:17
【问题描述】:

我想知道,你能创建一个带有可选参数的函数吗?

例子:

function parameterTest(test)
{
   if exists(test)
   {
     alert('the parameter exists...');
   }
   else
   {
     alert('The parameter doesn\'t exist...');
   }
}

因此,如果您调用parameterTest(),那么结果将是一条消息“参数不存在...”。如果你打电话给parameterTest(true),那么它会返回“参数存在......”。

这可能吗?

【问题讨论】:

  • 这是一个非常古老的问题,但显然每天都会查看,感谢您的输入。我编辑了原始帖子以使其更清晰。
  • 我认为现实世界的情况是如何检查函数的参数。 controllerservicemodel 层。会有很多参数需要检查。

标签: javascript function


【解决方案1】:

这是一种非常常见的模式。

您可以使用它进行测试

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

然后您可以使用其中一种形式调用您的函数:

 parameterTest();
 parameterTest(someValue);

注意不要让测试频繁出错

if (!bool) {

因为您无法将未提供的值与 false0"" 区分开来。

【讨论】:

  • -1 建议 === undefined - 在您的代码之前尝试 var undefined = true 看看会发生什么...正确的检查是 typeof book === 'undefined'
  • @griffin 如果有人在他们的代码中写了var undefined,他们应该受苦。 window.undefined 是不可写的,原因与 window.infinitywindow.NaN 相同 - 它们应该用于表示规范定义的各自值。
  • @griffin 你说得对。我们应该停止使用undefined,它随时可能改变!还不如停止使用ObjectDate,可能有人篡改了它们,你永远不应该相信document.createElement,它可能会被覆盖!
  • @griffin 绝对是,undefined 是一个局部变量。这就是为什么it's a property of the global object,显然是Object can't be overwritten
  • @griffin 简而言之:undefinedObject 具有完全相同的状态:它是由规范定义的全局对象的不可写(从 ES5 开始)属性,如果你隐藏它,它就是你的错。没有理由使用其中一个而不是另一个。此外,如果您正在编写用户脚本的页面确实重新定义了一个或另一个,greasemonkey still 通过为每个用户脚本提供单独的全局范围来保护您免受这种情况的影响。
【解决方案2】:
function parameterTest(bool)
{
   if(typeof bool !== 'undefined')
   {
     alert('the parameter exists...');
   }
   else
   {
     alert('The parameter doesn\'t exist...');
   }
}

【讨论】:

    【解决方案3】:

    在 JavaScript 中,如果您忽略提供参数,它将默认为 undefined

    您可以在浏览器控制台中或使用JSFiddle 自己轻松地尝试一下。

    你可以检查参数的存在,就像你说的那样,编写一个可以使用参数的函数。但是,JavaScript Garden(一个很好的资源)建议在大多数其他情况下远离typeof,因为它的输出几乎没有用(查看results of typeof 的表格)。

    【讨论】:

    • 作为替代方案,jquery 确实提供了一个$.type 方法,该方法在浏览器中始终如一地工作。
    • 那个链接说 typeof 只对这种情况有用,这足以解决这个问题。
    【解决方案4】:

    最好的检查方法:如果 param 不是 undefined

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

    参数也可以是变量或函数名

    【讨论】:

      【解决方案5】:
      function parameterTest(p) {
          if ( p === undefined)
              alert('The parameter doesn\'t exist...');
          else
              alert('the parameter exists...');
      }
      

      【讨论】:

        【解决方案6】:

        如果不存在则初始化默认值:

        function loadDialog(fn, f, local, anim) {
          switch (arguments.length) {  
            case 1: f=null;
            case 2: local=false;
            case 3: anim=false;
          }
          ...
        }
        

        【讨论】:

        • 请考虑解释您的代码以及它将如何提供帮助,以便其他人可以从中受益。
        • 这对我来说是正确的答案,因为我需要区分根本没有传递的值与将未定义的值传递给函数。其他答案不考虑传递未定义。
        【解决方案7】:

        这些答案都不适合我。我需要知道是否有人使用过这个参数。如果有人调用传递undefined 的函数,我想将其视为他们使用该值作为参数。无论如何,使用一些现代 JS 解决方案非常简单:

        function parameterTest(...test) {
          if (test.length) {
            return `exists`;
          } else {
            return `not exists`;
          }
        }
        
        parameterTest(123);         // exists
        parameterTest(undefined);   // exists
        parameterTest();            // not exists
        parameterTest(window.blah); // exists
        

        对于较旧的浏览器,您可以使用参数:

        function parameterTest() {
          if (arguments.length) {
            return "exists";
          } else {
            return "not exists";
          }
        }
        

        【讨论】:

        • 已经添加了相同的答案。不过,您更好地解释了这个问题。
        • 谢谢!忽略undefined 的二十个答案,然后是这个。 +1 表示通用解决方案,并且鼓励arguments 伪数组的古老艺术。
        【解决方案8】:

        null == undefined 是真的

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

        代码示例:

        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>

        【讨论】:

          【解决方案9】:

          我知道这是旧的,但这是我首选的检查方式,并为函数分配默认值:

          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
          }
          

          【讨论】:

            猜你喜欢
            • 2010-12-12
            • 2015-06-20
            • 2012-01-25
            • 2013-06-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多