【问题标题】:How to call function with sometimes less argument如何使用有时较少的参数调用函数
【发布时间】:2022-07-16 02:03:10
【问题描述】:

我想创建一个函数,例如:

var func = function(arg1, arg2) {
    callAnotherFunc(arg1, arg2);
}

如您所见,当有人需要调用func 时,它需要传递2 个参数。有时,arg2 可以为空。

有时,arg2 将为空。有什么捷径可以让我这样做吗?

var func = function(arg1, arg2) {
    callAnotherFunc(arg1, arg2 || nothing);
}

因此,如果 arg2 为 null,则根本不应该将另一个参数传递给 callAnotherFunc。我正在寻找一些捷径而不是if/else

【问题讨论】:

标签: javascript


【解决方案1】:

你可以试试这样的

How To Use ES6 Arguments And Parameters

var func = (...args) => {
    callAnotherFunc(...args);
}

var callAnotherFunc = (...args) =>{
  console.log(...args)
}

func(1);

func(1,2);

func(1,2,3);

【讨论】:

  • 看起来不错。然而更改func的签名并不真正考虑So if arg2 is null, it shouldn't pass another argument to callAnotherFunc at all.
  • 调用callAnotherFunc(...args.filter(arg => arg !== null))时可以过滤args
  • 你可以,但你没有这样做。这也将省略第一个参数。
【解决方案2】:

您可以使用call 转发所有不是nullarguments

var callAnotherFunc = function(){
  console.log(arguments)
};

var func = function(arg1, arg2){
    //So if arg2 is null, it shouldn't pass another argument to callAnotherFunc at all. 
    callAnotherFunc.call(
      null,
      Array.from(arguments).filter(function(item, index){
        return index == 0 || item !== null
      })
    )
};

func(1, 2);
func(1, null); //REM: Does not pass second argument
func(null, null); //REM: Does not pass second argument

【讨论】:

    【解决方案3】:

    我不明白你为什么要这样做,也许你的意图超出了我的理解。你可以使用default parameters

    var func = function(arg1, arg2 = null) {
        callAnotherFunc(arg1, arg2);
    }
    
    var callAnotherFunc = function(arg1, arg2 = null){
        // console.log(arg1);
        // console.log(arg2);
    }
    

    【讨论】:

      【解决方案4】:

      不,没有。只需使用if / else

      【讨论】:

        【解决方案5】:
        var func = function(...args) {
            // args will be an array of all the arguments
            if (args[1] == null) args.splice(1, 1);
            callAnotherFunc.apply(this, args);
        }
        

        【讨论】:

        • 虽然这段代码 sn-p 可以解决问题,但它没有解释为什么或如何回答这个问题。请include an explanation for your code,因为这确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
        • 感谢卢卡的建议。以后我会努力提高答案质量和解释。
        【解决方案6】:

        var func1 = function(arg1, arg2) {
            console.log(arg1, arg2);
        }
        
        var func = function(arg1, arg2) {
            arg2 && func1(arg1, arg2);
        }
        
        func(1, 2);
        
        func(1); // not consoled

        【讨论】:

          猜你喜欢
          • 2015-08-01
          • 2016-09-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多