JavaScript logic problem

0

I am asking you to print only the name and notes. But it is doubling at the time of printing. That is ... If I typed John, 1,2,3,4; Pedro, 3,4,5,6. At the time of printing, it prints twice the same thing.

//criar sala de aula com 4 alunos que possuem 4 notas e depois calcular a média de cada aluno.
//Sem objeto

var sala = [];
var aluno = [];

for (var i = 0; i < 4; i++) {
  for (var j = 0; j < 5; j++) {
    if (j == 0) {
      aluno.push(prompt("Digite o nome"));
    } else {
      aluno.push(prompt("Digite a nota"));
    }

  }
  sala.push(aluno);
}
console.info(sala.length);
for (var i = 0; i < sala.length; i++) {
  for (var j = 0; j < sala[i].length; j++) {
    if (j == 0) {
      console.log(sala[i][j]);
    } else {
      //console.log(parseFloat(sala[i][j]));
      console.log(sala[i][j]);
    }
  }
}
    
asked by anonymous 27.05.2017 / 01:12

2 answers

0
  

In the statement, it asks to create one room, and four students, and these with four notes . But when creating your variables, you create one student only :

var sala = [];
var aluno = []; // <- isso deveria representar apenas 1 aluno
  

This in itself is not a problem, you could save more students in this same array , but then you would not need 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:
sala[0] , sala[1] , sala[2] and sala[3] will have reference to exactly the same object. For a "visual" example of what's going on, take a look at this fiddle .

This happens because in

28.05.2017 / 09:17
0

Only the student array was cleared at the beginning of the for:

//criar sala de aula com 4 alunos que possuem 4 notas e depois calcular a média de cada aluno.
//Sem objeto

var sala = [];

for (var i = 0; i < 4; i++) {
  var aluno = [];

  for (var j = 0; j < 5; j++) {
    if (j == 0) {
      aluno.push(prompt("Digite o nome"));
    } else {
      aluno.push(prompt("Digite a nota"));
    }

  }
  sala.push(aluno);
}
console.info(sala.length);
for (var i = 0; i < sala.length; i++) {
  for (var j = 0; j < sala[i].length; j++) {
    if (j == 0) {
      console.log(sala[i][j]);
    } else {
      //console.log(parseFloat(sala[i][j]));
      console.log(sala[i][j]);
    }
  }
}
    
27.05.2017 / 01:33