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

97
Views
Mostrar objeto de matriz en js

Tengo un objeto de matriz.

Quiero mostrarlo antes y después de ordenarlo.

mi código es:

 const obj = [ { name: "ahmad", family: "mahdavi", city: "esf", score: 10 }, { name: "ali", family: "Ahmadi", city: "ahv", score: 5 }, { name: "reza", family: "rezaei", city: "tehran", score: 3 }, { name: "mohammad", family: "kiani", city: "shiraz", score: 19 } ]; let txt = ""; document.getElementById("p1").innerHTML = dis(); obj.sort( function (a, b) { return a.score - b.score; } ) document.getElementById("p2").innerHTML = dis(); function dis() { obj.forEach(element => { txt += element.name + " " + element.family + " " + element.city + " " + element.score + "<br>"; }) return txt; }
 <p id="p1"></p> <p id="p2"></p>

Debería mostrar los datos 2 veces, pero los muestra 3 veces. ¿Por qué?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

Esto sucede porque su variable txt es global y sigue recopilando datos. Debe convertirlo en una variable local, de modo que comience desde cero cada vez que llame a dis :

 const obj = [ { name: "ahmad", family: "mahdavi", city: "kian", score: 10 }, { name: "ali", family: "Ahmadi", city: "Shahrekord", score: 5 }, { name: "reza", family: "rezaei", city: "tehran", score: 3 }, { name: "mohammad", family: "kiani", city: "shiraz", score: 19 } ]; document.getElementById("p1").innerHTML = dis(); obj.sort( function (a, b) { return a.score - b.score; } ) document.getElementById("p2").innerHTML = dis(); function dis() { var txt = ""; // <--- obj.forEach(element => { txt += element.name + " " + element.family + " " + element.city + " " + element.score + "<br>"; }) return txt; }
 <p id="p1"></p> <p id="p2"></p>

about 4 years ago · Santiago Gelvez 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!