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

61
Views
javascript foreach en una matriz

Tengo una matriz que consta de 0, 1 y una "X" y estoy tratando de usar el método "forEach ()" para encontrar la "X" y reemplazarla con otro valor. ¿Cómo haría exactamente eso?

 let a=new Array for(int i=0;i<=5;i++) { a[i]=new Array for(int j=0;j<=5;j++) { a[i][j]=Math.round(Math.random()) } } a[3][2]="X" //the indexes are random values for(int i=0;i<=5;i++) { for(int j=0;i<=5;j++) { if(a[i][j]=="X") { a[i][j]="found" break } } }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

let matrix1 = [ [0, 1, 0, 1, 1], [1, 0, 1, 1, 1], [0, 1, 1, 0, 0], [1, 0, 1, 0, 1], [0, 1, 1, 'x', 1] ]; matrix1 .forEach((element1, index1, array1) => { element1.forEach((element2, index2, array2) => { if(array1[index1][index2] == 'x') { array1[index1][index2] = 'y'; } }); });

Puede haber otras (y mejores soluciones), pero esto debería funcionar. Pero recomendaría quedarse con los dos anidados para bucles.
Para el enfoque forEach , se deben crear dos funciones lambda y, cuando se las llama, ocurre un cambio de contexto (no estoy seguro de eso, el intérprete de javascript podría optimizarlo/eliminarlo). Por lo tanto, la huella de memoria podría ser un poco más alta y el rendimiento probablemente más bajo. Pero para una matriz de 5x5 nada de eso es importante.
Los bucles simples también son mucho más legibles, al menos para mí;)

about 4 years ago · Juan Pablo Isaza Report

0

En lugar de hacerlo con forEach, estaría usando el bucle for-of.

 let matrix = [ [0, 1, 0, "x", 1], [1, 0, 1, 1, 1], [0, "x", 1, 0, 0], ["x", 0, 1, 0, 1], [0, 1, 1, 0, 1] ]; for (const [i, row] of matrix.entries()) { for (const [j, element] of row.entries()) { if (element === "x") { matrix[i][j] = "Boom"; } } }

Final, la salida sería:

 [ [0, 1, 0, "Boom", 1], [1, 0, 1, 1, 1], [0, "Boom", 1, 0, 0], ["Boom", 0, 1, 0, 1], [0, 1, 1, 0, 1] ]
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!