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

207
Vistas
function to return something x amount of times,specified by a parameter?

I have a function which returns an html element like addSpan(times),is there a way to return this element as many times as specified in the parameter items ?

vanilla js is welcomed!

function addSpan(times){
 const span = `<span>This is a span</span>`
 
 return span
}

$("body").append( addSpan(2) ) //is supposed to add 2 spans
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
</body>
</html>

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Please use Array.map() function.

function addSpan(times){
  const spans = [...Array(times)].map(val => "<span>This is a span</span>").join('')
  return spans
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

use yield

function* addSpan(times){
  for(var i=0; i < times; i++){
    const span = document.createElement('span');
    span.innerText = "Some text" ;
    yield span;
  }
}


for (let element of addSpan(2)) {
  $("body").append(element)
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
</body>
</html>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Yes. Possible.

Like this:

function addSpan(count)
{
   let result = "";
   for (var i = 0; i < count; i++)
   {
     result += "<span>This is a span</span>";
   }
   return result;
}
about 4 years ago · Juan Pablo Isaza 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