Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

194
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda