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

224
Visualizações
Why am I getting an error with this multidimensional array?

I'm still new to Javascript and trying to understand multi-dimensional arrays. Why does the following code work?

var occupied = [[],[]];
occupied[1][0] = 0;
console.log(occupied[1][0]);

Yet, this code does not work.

var occupied = [[],[]];
occupied[2][0] = 0;
console.log(occupied[2][0]);

It also works with occupied[0][0]. Just not anything above 1.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

That's because you have defined only two items in your array (index 0 and index 1). So there is no index 2.

//      index:   0   1
var occupied = [ [], [] ];
occupied[1][0] = 0;
// works, index 1 exists
console.log(occupied[1][0]);
// error, index 2 doesn't exist
console.log(occupied[2][0]);

about 4 years ago · Juan Pablo Isaza Relatório

0

Size of your occupied array is 2 . So the maximum index you can access is 1. If you try to access any index above 1 it means that you are accessing undefined.

Now , as line 2 is, occupied[2][0] = 0 ; here occupied[2][0] is undefined and you cannot store anything inside undefined , which is causing you an error :)

about 4 years ago · Juan Pablo Isaza Relatório

0

occupied[1][0] = 0; works because the length of occupied is 2. occupied[1] will access the second node, which is an empty array occupied[1][0] = 0; this will assign 0 to the first element of the second node of occupied array.

var occupied = [
  [], // Index 0
  [], // Index 1 => occupied[1][0] will access the first item of empty array in this location
];
occupied[1][0] = 0;
console.log(occupied[1][0]);
console.log(occupied);

occupied[2][0] = 0; this will not work. works because the length of occupied is 2. occupied[2] will try to access the third node occupied array, which donot exist. In this case occupied[2] is undefined. occupied[2][0] = 0; will try to set 0 to zeroth index of an undefined variable, this will throw a refrence errror like

Uncaught TypeError: Cannot set properties of undefined (setting '0')
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