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

120
Views
JavaScript genera una matriz 2D de tamaño dinámico vacía

Estoy tratando de crear una cuadrícula 2D vacía de tamaño dinámico utilizando matrices que pueden tener un porcentaje de un valor en coordenadas específicas, y el resto otro valor, todo asignado después de la generación. Encontré una solución adecuada, pero quería obtener alguna aclaración sobre por qué la implementación original no funcionó como se esperaba.

El código que funciona:

 const height = 5; const width = 5; const percentage = 0.2; // control percentage of certain value // grid construction const grid = new Array(height).fill().map(element => new Array(width)); // grid population for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const probability = Math.random(); grid[y][x] = probability > percentage ? 'x' : 'o'; } } console.log(grid); /* Example Output: [ ['x', 'x', 'x', 'o', 'x'], ['o', 'o', 'x', 'x', 'x'], ['x', 'x', 'x', 'x', 'x'], ['x', 'x', 'x', 'x', 'x'], ['x', 'x', 'o', 'x', 'o'] ] */

El problema surge cuando cambio el bloque 'construcción de cuadrícula':

 const height = 5; const width = 5; const percentage = 0.2; // control percentage of certain value // grid construction (doesn't work as intended) const row = new Array(width).fill(); const grid = new Array(height).fill(row); // grid population for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const probability = Math.random(); grid[y][x] = probability > percentage ? 'x' : 'o'; } } console.log(grid); /* Example Output: [ ['x', 'x', 'x', 'o', 'x'], ['x', 'x', 'x', 'o', 'x'], ['x', 'x', 'x', 'o', 'x'], ['x', 'x', 'x', 'o', 'x'], ['x', 'x', 'x', 'o', 'x'] ] */

Creo que entiendo por qué el primer bloque de código da el resultado deseado, pero por mi vida no puedo averiguar qué está mal en el segundo ejemplo.

Realmente agradecería alguna aclaración sobre lo que está pasando aquí.

Salud :)

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