【问题标题】:Way to check a bunch of parameters if they are set or not in JavaScript检查一堆参数是否在 JavaScript 中设置的方法
【发布时间】:2011-05-18 23:34:58
【问题描述】:

所以,这种情况经常发生在我身上,但这是我最新的一个:

  var generic_error = function(title,msg){
        if(!title){ title= 'Oops!'; }
        if(!msg) { msg = 'Something must have gone wrong, but no worries we\'re working on it!'; }
        $.fancybox(
        {
            content:'\
                <div class="error_alert">\
                    <h2>'+title+'</h2>\
                    <p>'+msg+'\
                </div>'
        });
    }

有没有一种更简洁的方法来检查所有参数,如上面的titlemsg,或者将它们设置为可选,或者在函数中定义默认值,例如 PHP 是如何做到的?有时我可以有 10 个选项,而 if(!var){var='defaults'} x 10 很恶心...

【问题讨论】:

    标签: javascript jquery function variables


    【解决方案1】:

    略短但等同于您现在所做的是使用“||” AKA "或" AKA "默认运算符"。

    title = title || 'Oops!';
     msg = msg || 'Something must have gone wrong, but no worries we\'re working on it!';
    

    【讨论】:

      【解决方案2】:

      我怀疑你会发现任何比 if(!title)title='DefaultTitle' 更短更简单的函数参数。

      但是,我什至会使用更长的形式使其更明确:if (title===null) title='DefaultTitle'

      这是一个带有答案的相关问题,但我认为它只会使您的代码更加复杂。 How can I access local scope dynamically in javascript?

      【讨论】:

        【解决方案3】:

        您可以将三元表示法用作recommended by this article,但形式更简单:

        var n = null;
        !title ? title = 'Oops' : n;
        

        你还得到了 arguments[] 数组,它保存了参数并且可以在循环中使用,如下所示:

        function test(one,two,three) {
          i=0;
          while(typeof(arguments[i]) != 'undefined') {
            alert(arguments[i++]);
          }
        }
        
        test(40,27,399);
        

        【讨论】:

          【解决方案4】:
          switch (arguments.length) {
            case 0: title = 'Oops';
            case 1: message = 'Something must have gone wrong...';
          }
          

          【讨论】:

            【解决方案5】:

            这是另一种方法。 argsOK函数有点复杂,调用起来很简单。

            //-----------------------------------------------------
            /*
            PURPOSE Ensures a function received all required arguments, no extra 
                    arguments & (if so specified) no arguments are empty.
            RETURNS True if the arguments validate, else false.
            */
            function argsOk(
                functionCallee  ,   // Caller's callee object
                allArgsRequired ,   // True = All arguments are required
                emptyArgsAllowed    // True = Empty arguments are allowed
            ){
                var ok = true;
                for (var i = 0; i < 1; ++i) {
                    var functionName = functionCallee.toString().split(' ')[1].split('(')[0];
                    var args = functionCallee.arguments;
                    var expectedArgCount = functionCallee.length;
                    var actualArgCount  = args.length;
                    if ((allArgsRequired && actualArgCount < expectedArgCount) ||
                        (actualArgCount > expectedArgCount)) {
                        error("Function " + functionName + " expected " + expectedArgCount + " arguments, but received " + actualArgCount + ".");
                        ok = false;
                        break;
                    }
                    if (emptyArgsAllowed) {
                        break;
                    }
                    for (var j = 0; j < args.length; ++j) {
                        if (args[j] != null && args[j].length == 0) {
                            error("Function " + functionName + "() received an empty argument.");
                            ok = false;
                            break;
                        }
                    }
                }
                return ok;
            }
            

            调用它的示例(如您所见,单行):

            //------------------------------------------------
            function image(item, name, better)
            // PURPOSE Write a request for picture or photo
            // ENTRY        Init() has been called
            {
                if (!showingShortVersion()) {
                    var betterString = '';
                    if (better != null && better == true)
                        betterString = 'better ';
                    if (argsOk(arguments.callee, true, false))
                        write('<p class="request maintain">If you have ac&shy;cess to a ' + betterString + item + ' of ' + name + ' that we could put on&shy;line, please <a href="misc/pics.htm" onmouseover="return stat(\'Learn how to send us images\')" onmouseout="return erase()">click here</a>.</p>');
                }
            }
            

            【讨论】:

              【解决方案6】:

              一般来说,尤其是在 Javascript 中,clean != short。

              不要将if(!title){ title= 'Oops!'; } 用作通用 解决方案,因为例如0 和空字符串也是虚假的。未设置的参数是undefined,所以我更喜欢使用

              if (title === undefined) {
                  title= 'Oops!'; 
              }
              

              这样做可能会比较冗长,但它会防止不必要的副作用,而且根据我的经验,如果您尝试使用快捷方式,Javascript 会产生很多不必要的副作用。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2019-05-22
                • 1970-01-01
                • 2014-07-04
                • 1970-01-01
                • 2014-08-12
                • 1970-01-01
                • 1970-01-01
                • 2016-07-19
                相关资源
                最近更新 更多