【问题标题】:Pass in any number of arguments into a Javascript function [duplicate]将任意数量的参数传递给Javascript函数[重复]
【发布时间】:2023-04-03 05:40:01
【问题描述】:

我希望能够将任意数量的参数传递给函数,然后能够在以后使用这些参数。我知道我可以传入默认参数,但我不知道在我的函数中声明什么。

例如,

function test(????) {
  console.log(a)
  console.log(b)
  console.log(c)
}

test(a="a", b="b", c="c")

我也面临着被赋予这个功能并尽可能少地改变 var 声明的挑战。所以这里声明了变量 a、b 和 c,我无法编辑这些变量。我应该能够传入参数,然后知道将自己分配给这些变量。

function test(???) {
  var a,b,c
  if (a>b){
    c = a + b
  }
}

test(a=2,b=3)

【问题讨论】:

标签: javascript


【解决方案1】:

你应该使用数组或对象。

在该数组中添加任意数量的参数。

function test(arr) {
   console.log(arr.a);
   console.log(arr.b);
   console.log(arr.c);
}

arr = {}
   
arr.a = "a";
arr.b = "b";
arr.c = "c";
    
k = test(arr);
    
    

【讨论】:

  • 这就是我的想法,除了我正在使用一个预先设置变量的函数,这意味着我无法更改 var 声明。我必须确保传递给函数的内容,我的参数需要与函数内部的相应声明连接。
  • @jamesvphan 这不是问题,只需将它们分配给新创建的对象即可。
【解决方案2】:

你可以传入一个对象或数组:

function test1([a, b, c]) {
   // ...
}
test1([1, 2, 3]);

function test2({ a, b, c }) {
   // ...
}
test2({ a: 1, b: 2, c: 3 });

【讨论】:

    【解决方案3】:
    function test(input) {
      console.log(input.a);
      console.log(input.b);
      console.log(input.c);
    }
    
    test({ a: 1, b: 2, c: 3 });
    

    【讨论】:

      【解决方案4】:

      您实际上不需要在函数参数中定义任何参数。您需要做的就是访问javascript 内置的arguments 对象。

      所以您的代码可能如下所示:

      function test() {
          var a = arguments[0];
          var b = arguments[1];
          var c = arguments[2];
      
          console.log(a);
          console.log(b);
          console.log(c);
      }
      
      test("a", "b", "c");
      

      供参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

      【讨论】:

      • 这太棒了!我需要什么!
      【解决方案5】:

      使用数组是个好主意,但为了完整性...

      ES6 方式!

      如果您能够支持 ES6 功能,spread operator 与 arguments 关键字相结合是一种巧妙的解决方法:

      function anyNumber() {
        console.log(...arguments); // ->  1 2 3 4
      
        let argsAsArray = [0, ...arguments, 5]; // now they're an array
      
        argsAsArray.forEach(s => console.log(s)); // -> 0 1 2 3 4 5
      };
      
      anyNumber(1,2,3,4);
      

      使用扩展运算符可以做很多很酷的事情,尤其是对象和参数解构。

      【讨论】:

      • 是的,我认为在这种情况下解构是我的最佳选择
      【解决方案6】:

      在更新的问题中给定javascript,您可以在函数名称后的() 中定义默认参数。

      function test(a = 2, b = 3) {
        let c;
        if (a > b) {
          c = a + b
        } else {
          c = 0
        }
        console.log(c);
      }
      
      test(); // 0
      
      test(4); // 7

      另见Can we set persistent default parameters which remain set until explicitly changed?

      【讨论】:

      • 我认为这是我需要的,但是代码 sn-p 给我一个来自 fn(...opts) 函数的错误
      • @jamesvphan 该错误可能是由于使用了对象休息{...opts.map((prop, index)}。对象休息{a, b, ...rest} 可在铬,铬使用--javascript-harmony 标志;或独立使用babel。将在 stacksn-ps 启用 babel
      • @jamesvphan 查看更新的 stacksn-ps
      猜你喜欢
      • 1970-01-01
      • 2017-12-18
      • 2014-03-26
      • 2022-06-27
      • 2012-11-13
      • 1970-01-01
      • 2012-09-24
      • 2013-07-09
      相关资源
      最近更新 更多