代码之家  ›  专栏  ›  技术社区  ›  Upgradingdave

Javascript:将数组作为可选方法参数传递

  •  1
  • Upgradingdave  · 技术社区  · 14 年前

    更新:以下是我的解决方案(受公认答案启发):

    function log(msg, values) {
             if(config.log == true){
             msg = [msg];
             var args = msg.concat(values);
             console.log.apply( this, args );
             }
         }
    

    更新2:更好的解决方案:

     function log(msg) {
         if(config.log == true){
         msg = [msg];
         var values = Array.prototype.slice.call(arguments, 1);
         var args = msg.concat(values);
         console.log.apply( console, args );
         }
     }
    

    log("Hi my name is %s, and I like %s", "Dave", "Javascript");
    

    原来的问题是:

    console.log

    console.log("My name is %s, and I like %", 'Dave', 'Javascript')
    

    My name is Dave, and I like Javascript
    

    我想把它包装成这样一个方法:

    function log(msg, values) {
      if(config.log == true){
        console.log(msg, values);
       }
     }
    

     log("My name is %s, and I like %s", "Dave", "Javascript");
    

    我明白了(它不承认“Javascript”是第三个参数):

     My name is Dave, and I like %s
    

     log("My name is %s, and I like %s", ["Dave", "Javascript"]);
    

    然后它将第二个arg当作一个数组(它不会扩展到多个arg)。我错过了什么技巧来让它扩展可选参数?

    4 回复  |  直到 14 年前
        1
  •  2
  •   azatoth    14 年前

    以下可能有效(未经测试):

    function log(msg, values) {
      if(typeof config.log != 'undefined' ) {
        if( typeof values != 'Array' ) {
          values = [values];
        }
        values.unshift( msg );
        console.log.apply( this, values );
      }
    }
    
        2
  •  2
  •   SLaks    14 年前

    你在找 arguments 标识符,它是一个类似数组的对象(但不是实际的数组),包含传递给函数的所有参数。

    在您的示例中,可以得到一个数组,其中包含第一个参数之后的所有参数,如下所示:

    var values = Array.prototype.slice.call(arguments, 1);
    
        3
  •  1
  •   mVChr    14 年前

    function log(msg, values) {
    
        if (undefined != console) {
            var newArg = '';
            var newMsg = msg.split('%s');
    
            if (undefined != values) {
                for (i=0; i < (newMsg.length-1); i++) {
                    newArg += newMsg[i] + values[i];
                }
            } else {
                newArg = newMsg[0];
            }
    
            console.log( newArg );
        }
    
    }
    
        4
  •  -2
  •   Matthew Smith    14 年前

    编辑: 我很惊讶这不起作用,所以我回去,看看上面所有的。

    log("My name is %s, and I like %s", 'Dave', 'Javascript');
    

    最简单的解决办法是:

    function log() {
        if(console.log !== null){
            console.log.apply(console,arguments);
        }
    }
    

    哦,还有 console.log == true 在FF和Chrome中都不适合我。仅限 console.log != null 工作。在IE7里什么都没用,想想看。

    原始(错误)答案:

    Javascript有一个特殊的“arguments”变量,它完全满足您的需要。

       function log(msg, arguments) {
           if(config.log == true){
             console.log(msg, arguments);
           }
       }