0

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?

0

1 Answer 1

1

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);
}

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.