Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda