Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript中的可选参数优先_Javascript - Fatal编程技术网

JavaScript中的可选参数优先

JavaScript中的可选参数优先,javascript,Javascript,为了方便用户,我有一个函数,它首先接收一个可选参数,然后再接收所需参数。例如: ns.myFunction('optional arg', function(){ //the required callback }); 我这样做,而不是执行以下操作,因为回调主体可能很长,用户可能忘记覆盖可选参数的默认值: ns.myFunction(function(){ //the required callback }, 'optional arg'); function myFunct

为了方便用户,我有一个函数,它首先接收一个可选参数,然后再接收所需参数。例如:

ns.myFunction('optional arg', function(){
    //the required callback
});
我这样做,而不是执行以下操作,因为回调主体可能很长,用户可能忘记覆盖可选参数的默认值:

ns.myFunction(function(){
    //the required callback
}, 'optional arg');
function myFunction(options, callback);
目前,我这样做是为了检查:

function myFunction(first, second) {

    //if second is undefined and first is a function
    if (typeof second === 'undefined' && typeof first === 'function') { 
        second = first;
    }
}
问题

  • 这条路对吗
  • 我该如何做才能使其扩展,特别是如果在必需参数之前有N个可选参数

    • 无需命名任何参数。你可以简单地说:

      if (arguments.length < 2)  // There are no optional parameters
      
      if(arguments.length<2)//没有可选参数
      
      并通过参数[i]检索每个参数。该函数位于参数[arguments.length-1]处

      请注意,typeof运算符总是返回一个字符串,因此可以使用==代替===

      这不是正确的方法,因为根据惯例,可选参数总是放在末尾。你会发现一个原因:处理它们要容易得多。如果您关心匿名函数的长度,则API的客户端应使用函数引用或变量:

      function callback1() { //...
      
      var callback2 = function() {//...
      
      myFunction(callbackX, optional);
      
      转义
      的问题可以通过
      bind()
      解决

      如果您真的想使用多个可选参数并在最后回调,我可以想到两种方法:
      参数
      对象或将所有可选参数包装在一个
      选项
      对象中

      使用
      参数
      可以编写:

      var lastOptionalIndex = arguments.length - 2;
      var callback = arguments[lastOptionalIndex + 1];  //required callback is always last
      var optionalFirst = lastOptionalIndex >=0? arguments[0] : undefined;
      var optionalSecond = lastOptionalIndex >=1? arguments[1] : undefined;
      //...
      
      看看它相比之下有多丑陋:

      function myFunction(callback, firstOptional, secondOptional //...
      
      使用
      options
      wrapper对象时,始终有两个参数:

      ns.myFunction(function(){
          //the required callback
      }, 'optional arg');
      
      function myFunction(options, callback);
      
      其中,
      options
      只是一个对象:

      {
        firstOptional: 1,
        secondOptional: 'foo'
        //...
      }
      

      如果确实要首先传递多个可选参数,可以这样做:

      function myFunction() {
          alert("optional:");
          for(var i=0; i<arguments.length-1) alert(arguments[i]);
          alert("function: "+ arguments[arguments.length-1]);
      }
      
      函数myFunction(){
      警报(“可选:”);
      
      对于(var i=0;i而言,可通过以下方法轻松完成:


      <> P>一个非常相似的例子,注意只需要中间的参数:

      function range(){ 
        arguments = __({start: [Number, 0], stop: Number, step: [Number, 1]})
      
        for(var i = arguments.start; i < arguments.stop; i += arguments.step)
          console.log(i);
      }
      
      ArgueJS:

      function range(){ 
        arguments = __({start: [Number, 0], stop: Number, step: [Number, 1]});
        for(var i = arguments.start; i < arguments.stop; i += arguments.step)
          console.log(i);
      }
      

      您可以配置函数参数,具体取决于它们的数量:

      myFunction() {
          let first, second;
          if (arguments.length === 2) {
              [first, second] = arguments;
          } else if (arguments.length === 1) {
              [second] = arguments;
          }
          if ( ! first) {
              // first is undefined, so only second argument was passed.
          }
      }
      

      ES6解构使代码干净且适合扩展。

      一种简单的功能方法:

      想法:

    • 编写一个函数myFunction(必选,可选),其中可选参数是最后一个,因此很容易 处理
    • 使用函数appendFirstArgumentIf()在myFunction之外创建新函数myNewFunction(可选,必需)
    • 如果函数appendFirstArgumentIf传递testfunction,则调用myFunction,并将第一个参数移动到最后一个位置,否则不会更改参数
    • _

      用法:

      function myFunction(callback, string){
          string = string ? string : 'Default Message'
          callback(string)
      }
      
      var myNewFunction = appendFirstArgumentIf(myFunction,
                                                firstArgument=> typeof firstArgument !== 'function')
      
      
      myNewFunction('New Message', console.log)  // using console.log as callback function
      //>>>New Message
      myNewFunction(console.log)
      //>>>Default Message
      
      这也有可能:

      function mySecondFunction(callback, name, string){
      string = string ? string : 'Welcome'
      callback(string, name)
      }
      
      var myLatestFunction = appendFirstArgumentIf(mySecondFunction,
                                            firstArgument=> typeof firstArgument !== 'function')
      
      
      myLatestFunction('Hello', console.log, 'John')
      //>>>Hello John
      myLatestFunction(console.log, 'John')
      //>>>Welcome John
      
      功能测试(num=1){
      console.log(typeof num)
      }
      test()/“number”(num设置为1)
      测试(未定义)/“数字”(num也设置为1)
      //使用其他falsy值进行测试:
      测试(“”)/“字符串”(num设置为“”)
      
      test(null)/'object'(num设置为null)
      为什么不将可选参数放在参数列表的末尾?这在JavaScript中更有用,因为
      .bind()
      的语义。更“稳定”的参数应该放在第一位,而最有可能变化或在末尾不存在的参数。使用
      参数怎么样[…]
      ?不会在数组中迭代,并在参数的第一个
      类型处停止[i]==“function”
      帮助?“为了方便用户”-这会使函数更加混乱,并且与IDEs@Stecman对于长且深度缩进的回调(如100行或更多行),从一开始就可以很方便地看到可选的,而不是从最后才看到。我认为jQuery实际上就是这样做的。
      .extend
      函数是一种特殊情况,它有两种可选参数;有人可能会说它最好是两个独立的函数,但这样的参数是不正确的illy:-)是的,在回调函数之前或之后使用options对象参数是一个很好的方法。它使使用extend方法分配默认值变得更容易。
       /**
       * @param {function} fn(a,...b)
       * @param {function} argumentTest - a function to test the first parameter
       * @return {function} returns a function that passes its first argument into 
        argumentTest. If argumentTest returns true, fn is called with the first 
        argument shifted to the last position else fn is called with the arguments 
         order unchanged
       */
      function appendFirstArgumentIf (fn,argumentTest){
         return function(a,...b){
             return argumentTest(a) ? fn(...b,a) : fn(a,...b) 
         }
      }
      
      function myFunction(callback, string){
          string = string ? string : 'Default Message'
          callback(string)
      }
      
      var myNewFunction = appendFirstArgumentIf(myFunction,
                                                firstArgument=> typeof firstArgument !== 'function')
      
      
      myNewFunction('New Message', console.log)  // using console.log as callback function
      //>>>New Message
      myNewFunction(console.log)
      //>>>Default Message
      
      function mySecondFunction(callback, name, string){
      string = string ? string : 'Welcome'
      callback(string, name)
      }
      
      var myLatestFunction = appendFirstArgumentIf(mySecondFunction,
                                            firstArgument=> typeof firstArgument !== 'function')
      
      
      myLatestFunction('Hello', console.log, 'John')
      //>>>Hello John
      myLatestFunction(console.log, 'John')
      //>>>Welcome John