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

153
Visualizações
javascript, for-of in multidimensional array

i'm probably missing something about js array.

given this array:

let a = []

i add two more array

a["b"] = [1,2,3]
a["c"] = [4,5,6]

why its lenght is 0 ?

a.length
0

why i can't for-of?

for (const val of a) { console.log(val)}
undefined

but i can do for the inside array

for (const val of a["b"]) { console.log(val)}
1
2
3

what is wrong in what i'm doing here?

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

0

Arrays are generally meant to be collection of values only, which can be associated with a numeric index (integers starting with 0).

Arrays also happen to be objects, and objects can have arbitrary key-value pairs associated with them by assigning to a property of the object. For similar reasons, you can do this for functions:

function foo() {
}
foo.someProp = 'bar';
console.log(foo.someProp);

But, in both cases, this is pretty weird and should be avoided unless you're sure of what you're doing.

If you want to use an array, assign to numeric indicies of the array, or use push:

const a = [];
a.push([1,2,3]);
a.push([4,5,6]);
console.log(a);
console.log(a.length);

Using for..of on an array will only iterate over array-index property values. The b in a["b"] is not an array index, so it doesn't show up with for..of.

Similarly, the length of an array is determined by the number of array indicies that have been filled - if the [0] property exists, the length will be 1, If the [1] property exists too, the length will be 2 - and so on.

If you need non-numeric integer keys, use an object or Map instead:

const obj = {};
obj.b = [1,2,3]
obj.c = [4,5,6]
console.log(obj);
for (const item of obj.b) {
  console.log(item);
}

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