Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

314
Views
¿La lógica de forEach () cuando funciona con variables en javascript?

el resultado del código es:

 test0: apple 1: orange 2: cherry

Quiero saber por qué mi variable de texto es igual a "" en el segundo y tercer ciclo, esperaba que los valores anteriores se agregaran al valor inicial de la variable de texto. ¿Alguien puede explicar qué sucede con la variable de texto y cuál es la lógica? de forEach en este ejemplo?

 let text = "test"; const fruits = ["apple", "orange", "cherry"]; fruits.forEach(myFunction); document.getElementById("demo").innerHTML = text; function myFunction(item, index) { text += index + ": " + item + "<br>"; }
 <p id="demo"></p>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Su ciclo se ejecuta de tal manera que la test de texto solo se agrega una vez. Al principio y luego más tarde se actualiza el text variable.

Si desea agregar en cada iteración, simplemente manténgalo en una variable separada y siga agregando.

 let text = ""; let test = "test"; const fruits = ["apple", "orange", "cherry"]; fruits.forEach(myFunction); document.getElementById("demo").innerHTML = text; function myFunction(item, index) { text = text + test + index + ": " + item + "<br>"; }
 <p id="demo"></p>

about 4 years ago · Juan Pablo Isaza Report

0

Sus códigos funcionan como se esperaba. usar texto interno en lugar de HTML interno podría iluminar la situación

 let text = "test"; const fruits = ["apple", "orange", "cherry"]; //fruits.forEach(myFunction); document.getElementById("demo").innerText = text; function myFunction(item, index) { text += index + ": " + item + "<br>"; document.getElementById("demo").innerText = text; console.log(item,index); } window.setTimeout( myFunction.bind(null,fruits.shift(),0), 1000); window.setTimeout( myFunction.bind(null,fruits.shift(),1), 2000); window.setTimeout( myFunction.bind(null,fruits.shift(),2), 3000);
 <p id="demo"></p>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!