【问题标题】:unpacking rest (...theArgs) parameter before passing it to the function在将其余 (...theArgs) 参数传递给函数之前对其进行解包
【发布时间】:2022-09-30 23:28:24
【问题描述】:

我正在尝试调用所需的函数次数。为了解决这个问题,我正在创建一个接受rest 参数并遍历第一个参数的函数。我无法解压缩其余参数并将其传递给函数。有没有一种方法可以解压缩并将其作为参数传递给函数。下面是我的工作代码。有没有更好的方法让它发挥作用?

function hello(name) {
  console.log(\"Hello \"+ name);
}

function greet(name,time_of) {
  console.log(\"Good \" + time_of +\" \" +name);
}

function foo(times,x, ...args) {
    for(i=0;i<times;i++) {
    x(arguments)
    //x(args); //works good for hello() but not for greet(). Doesn\'t pass them to second argument
    x(args[0],args[1]); //This works but not scalable 
    //args.map((element) => x(element)); 

  }
}

foo(2,hello,\"Myname\");
foo(3,greet,\"Myname\",\"Afternoon\");

    标签: javascript decorator rest-parameters


    【解决方案1】:

    只是spread args 再次出现:

    function hello(name) {
      console.log("Hello " + name);
    }
    
    function greet(name, time_of) {
      console.log("Good " + time_of + " " + name);
    }
    
    function foo(times, x, ...args) {
      for (i = 0; i < times; i++) {
        x(...args)
      }
    }
    
    foo(2, hello, "Myname");
    foo(3, greet, "Myname", "Afternoon");

    【讨论】:

      猜你喜欢
      • 2019-02-11
      • 1970-01-01
      • 2021-11-09
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 2015-06-13
      相关资源
      最近更新 更多