Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

190
Visualizações
unpacking rest (...theArgs) parameter before passing it to the function

I am trying to call a function required number of times. To solve this, I am creating a function that takes rest parameters and iterating through the first argument. I am unable to unpack the rest arguments and pass it to the function. Is there a way that I could unpack and pass it to the function as parameters. Below is my working code. Is there a better way to make it work ? Thanks in advance. Appreciate any help.

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");
almost 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Just spread the args out again:

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");

almost 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda