Assign values to arrays

4

I noticed that by incrementing a value to a array using the following syntax:

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

length of this array is not incremented, and remains in 0 , even though array contains an item. What is the reason for this behavior?

    
asked by anonymous 12.08.2018 / 18:15

3 answers

4

JavaScript has some confusing things, one of which is that what the language calls array are actually two completely different structures with the same syntax and different semantics. What you are using is officially called array , but in practice it is a hash table, a dictionary, or you can even call it array > associative.

Pure array when the key that indexes the collection of values is numeric and sequential, as is a real array . And it has length . When using different keys and it behaves like a dictionary this property does not work because there is no official length, although technically it would be possible to keep something like this, there are other badly formulated questions in JS that makes this difficult.

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

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

let array = [];
array['nomeIndice'] = 10;
console.log(Object.keys(array).length);
    
12.08.2018 / 18:34
3

Just to add some more information to what @Maniero already said, if you use numerical indices, you still use the array as a normal array.

See with index 10 for example:

let array = [];
console.log(array, array.length);

array[10] = 2;
console.log(array, array.length);

Here you see that by setting the position 10 to a value, all previous positions were defined with undefined and at the end the array was 11 size.

But when assigning a non-numeric index 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 by accessing the key 'nomeIndice' the value is there in it.

The most correct syntax for this is even the object with {} , which makes it clear that you are dealing with braces 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);
    
12.08.2018 / 20:45
0

The correct one would be:

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

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

array.push(10);

    
12.08.2018 / 18:33