Logic problem in Javascript

Asked

Viewed 90 times

0

I am asking to print only the name and notes. However it is duplicating at the time of printing. Ie... If I typed John, 1,2,3,4; Peter,3,4,5,6. At the time of printing, he 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]);
    }
  }
}

  • What do you mean? Can you explain how it works? =/

  • 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.

  • Managed to resolve that issue?

  • Yes. Thank you very much.

  • Please accept one of the answers if they have helped you.

2 answers

0


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 , 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>

0

It was only necessary to reset the array of students at the start of the:

//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]);
    }
  }
}
  • Can you explain me better? Because in Java I created most of the variables outside. And I didn’t understand why I had to put inside the for =(

  • If you do not initialize inside the for, the array of students will only grow. By initializing the array of students within the loop you create a new array with each iteration and at the end stack it in the array of rooms.

  • In case I could keep out, but restart it after doing the sala.push; something like: alunos = []. Tip: For newer JS versions, do not use var, but yes let or const.

Browser other questions tagged

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