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

152
Views
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 answers
Answer question

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 Report
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!