In the statement, he asks to create one room, and four students, and these with four notes. Only, by creating your variables, you create one student only:
var sala = [];
var aluno = []; // <- isso deveria representar apenas 1 aluno
This in itself does not represent a problem, you could keep more students in this same array
, but then you wouldn’t need the array
sala
. See where the problem is:
for (var i = 0; i < 4; i++) {
for (var j = 0; j < 5; j++) {
if (j == 0) {
aluno.push(prompt("Digite o nome")); // aluno recebe 4 nomes
} else {
aluno.push(prompt("Digite a nota")); // e 16 notas
}
}
sala.push(aluno); // o mesmo aluno é passado para sala, 4 vezes
}
That is to say:
sala[0]
, sala[1]
, sala[2]
and sala[3]
will have reference to exactly the same object. For a "visual" example of what is occurring, take a look at this fiddle.
This is because in javascript, arrays are objects, and therefore are passed as reference for functions and not as copy of value as is the case of primitives.
The @joserogerio84 solution works, because it’s not just "zeroing" the array with every iteration, it’s creating a new.
See an example working below:
/*
* criar sala de aula com 4 alunos que possuem 4 notas
* e depois calcular a média de cada aluno.
* Sem objeto
*/
let sala = [];
let aluno = [];
let t = document.getElementById('table').getElementsByTagName('tbody')[0];
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 5; j++) {
if (j == 0) {
aluno.push(prompt("Digite o nome"));
} else {
aluno.push(prompt("Digite a nota"));
}
}
sala.push(aluno); // mandamos a referencia desse aluno para sala
aluno = []; // isso cria um novo array com o mesmo nome
}
for (let i = 0; i < sala.length; i++) {
let linha = t.insertRow(t.rows.length);
for (let j = 0; j < sala[i].length; j++) {
saida(linha, j, sala[i][j]);
}
}
function saida(linha, numero, texto) {
linha.insertCell(numero).appendChild(document.createTextNode(texto));
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 10px;
}
<table id="table">
<th>Nome</th>
<th>Nota</th>
<th>Nota</th>
<th>Nota</th>
<th>Nota</th>
</table>
What do you mean? Can you explain how it works? =/
– Thun An Freitas Chiu
So I started studying Javascript now, then I get lost with what I can and can’t. I wanted with Array even, after I’ll do with Object.
– Thun An Freitas Chiu
Managed to resolve that issue?
– Daniel
Yes. Thank you very much.
– Thun An Freitas Chiu
Please accept one of the answers if they have helped you.
– Daniel