Just to add a little more information to what @Maniero has already said, if you use numeric indices continue to use the array as a normal array.
See with the index 10
for example:
let array = [];
console.log(array, array.length);
array[10] = 2;
console.log(array, array.length);
Here you see that when defining the position 10
with a value, all previous positions have been defined with undefined
and at the end the array got size 11
.
But when assigning a non-numeric index it already behaves as if it were a dictionary with keys and values, not appearing this information where it would appear in an array:
let array = [];
console.log(array, array.length);
array['nomeIndice'] = 2;
console.log(array, array.length);
console.log(array['nomeIndice']);
But notice that accessing the key 'nomeIndice'
the value is there in the same.
The most correct syntax for this is the object with {}
, which makes it clear that you are dealing with keys and values, not an array where you would normally add values through push
without specifying the position:
let objeto = {};
console.log(objeto);
objeto['nomeIndice'] = 2;
console.log(objeto);
I don’t think this answers what he asked.
– Maniero