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

124
Vistas
Creating multidimensional arrays on-the-fly

Take the following function to generate a square multiplication table:

function getMultTable(n) {
    /* generate multiplication table from 1 to n */
    let table = new Array(n);
    for (let i=1; i<=n; i++) {
        table[i-1] = new Array(n);
        for (let j=1; j<=n; j++) {
            table[i-1][j-1] = i*j;
        }
    }
    return table;
}

console.log(getMultTable(3));
// [ 
//   [ 1, 2, 3 ], 
//   [ 2, 4, 6 ], 
//   [ 3, 6, 9 ]
// ]

Why can't the following be done instead?

function getMultTable(n) {
    let table = new Array(n);
    for (let i=1; i<=n; i++) {
        for (let j=1; j<=n; j++) {
            table[i-1][j-1] = i*j;
        }
    }
    return table;
}

In other words, why can't a multi-dimensional array be created on-the-fly in javascript, or is it possible to do that some other way?

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

0

Let's start from the basics, why you can't do the following

let arr;
arr[0] = 1

The answer is because arr is undefined. Well, when an array is initialized it is initialized with all its entries undefined. The operation table[i-1][j-1] = i*j is equivalent to

const row = table[i-1];
row[j-1] = i*j

So, when the table is created all its items are undefined, and the statement row[j-1] = i*j, is trying to set a property of row, in other words setting a property of undefined.

The reason is similar to why you can't run this

function getMultTable(n) {
    let table;
    for (let i=1; i<=n; i++) {
        for (let j=1; j<=n; j++) {
            table[i-1][j-1] = i*j;
        }
    }
    return table;
}

Only that in this case your problem is trying to read a property from undefined

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can do it something like this:

let arr = new Array(n).fill().map(el => new Array(n).fill());
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