Assign values to arrays

Asked

Viewed 718 times

5

I realized that by increasing a value to one array using the following syntax:

let array = [];
array['nomeIndice'] = 10;

the length that array is not incremented, and continues in 0, despite the array contain an item. What is the reason for this behavior?

3 answers

5


Javascript has some confusing things, one of which is that what you’re using is officially called array, but in practice it’s a table hash, a dictionary, or may even be called array associative.

Only is array has a length. But it behaves like a dictionary this property does not work because there is an official length, although technically it would be possible to keep something like this, there are other poorly formulated issues in the JS that hinders this.

In a way a array of this type is equal to an object, it is considered that it has members and not elements, so a count would not make sense.

The solution to this is to get only the keys or only the values in one array and take the size of it. It has ready-made function that does it. So:

let array = [];
array['nomeIndice'] = 10;
console.log(Object.keys(array).length);

I put in the Github for future reference.

4

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

0

The right thing would be:

let array = []; array[i] = 10;

You can use the method push(quaquer tipo de elemento) to add elements to the array, thus:

array.push(10);

  • 3

    I don’t think this answers what he asked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.