【问题标题】:javascript define argumentsjavascript定义参数
【发布时间】:2019-01-05 13:49:13
【问题描述】:

我正在尝试在 JS 中创建一个函数,该函数接受很多参数,但并不总是使用所有参数。我想做的是定义我要引用的论点。这就是我的想法,但没有像我希望的那样工作。

function foo(arg1, arg2, arg3){
let arg1 = arg1;
let arg2 = arg2;
let arg3 = arg3;

}

foo(arg2:'sets value of arg2');

我希望能够跳过为第一个位置输入参数而只为第二个参数传递信息。我该怎么做?

【问题讨论】:

标签: javascript function arguments


【解决方案1】:

您可以spread syntax ... 一个稀疏数组,其中包含所需参数的值,而无需更改函数的签名。

function foo(arg1, arg2, arg3){
    console.log(arg1, arg2, arg3)
}

foo(...[, 42]);

或者使用带有指定元素键的对象

function foo(arg1, arg2, arg3){
    console.log(arg1, arg2, arg3)
}

foo(...Object.assign([], { 1: 42 }));

【讨论】:

    【解决方案2】:

    试试这个:

    它需要调用者传递一个对象。

    function foo({arg, arg2}={}) {
      let arg_1 = arg;
      let arg_2 = arg2;
      
      console.log(arg_1);
      console.log(arg_2);
      // Code
    }
    
    foo({arg2: 2});

    如果需要设置默认参数可以这样function foo({arg = '', arg2 = ''}={})

    【讨论】:

    • 如果它对您有帮助,请做出正确的答案来帮助有需要的人,但这是一种乐趣
    【解决方案3】:

    如果不需要,可以将null作为一些参数传入。

    function foo(arg1, arg2, arg3){
    console.log(arg1, arg2, arg3);
    }
    foo(null, 30, null);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-31
      • 2011-09-25
      • 2021-05-17
      • 2011-06-06
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 2018-04-02
      相关资源
      最近更新 更多