I think you need to understand better what a function javascript.
Let’s check this part of the code:
aniversario.push(i) = {
nome: 'Thiago',
idade: 20
diaDoAniversario: '7/12/2020'
}
Note that you are calling the method Array.prototype.push
(push
), passing the variable value i
. This will insert (at the end of the array) the value of i
every iteration, until the loop ends.
But note that at the return of the method push
(which in this case is the new array length) you are trying to assign the literal object (note the assignment operator =
which, in that case, is not doing anything useful). It is the same thing as trying to assign an object to a number, thus:
// Este código não faz sentido e lançará um erro de sintaxe.
1 = { name: 'Foo' };
This makes no sense since you want to insert the object into the array. Therefore, you should call the push
passing, as argument, the very value you want to insert. In this case, it is the literal object itself.
You will then have something like this:
const aniversario = [];
for (let i = 0; i <= 10; i++) {
aniversario.push({
nome: 'Thiago',
idade: 20,
diaDoAniversario: '7/12/2020'
});
}
console.log('aniversario 8', aniversario[8])
console.log('Total de itens', aniversario.length)
You can even use the assignment to insert some value in a array, but it is not very necessary, since the push
does this for free. Anyway, to assign, you will need to use bracket notation:
let arr = [];
arr[0] = 'A';
arr[1] = 'B';
arr[2] = 'C';
console.log(arr); //=> ['A', 'B', 'C']
console.log(arr.length); //=> 3