Javascript - How to create two-dimensional arrays and loop them?

Asked

Viewed 66 times

0

For example, if I want to create an algorithm with 3 lines and 4 columns, in which each row is a student, and each column is the student’s grades (1st bimonth, 2nd bimonth, 3rd bimonth, 4th bimonth), how could it be done in Javascript? in languages like JAVA or C I’ve done, but in Javascript it doesn’t work, an example of how I tried in javascript, but it didn’t work:

var notas = [][];

for (let i = 1; i <= 3; i++) {
    notas[i] = prompt('NOME DO ALUNO: ');
    for (let y = 1; y < 5; y++) {
        notas[i][y] = Number(prompt(`${y}ºBIMESTRE: `));
    }
}
  • And the student’s name is in what position? 5th?

  • I visualize this as a two-dimensional matrix, imagine an excel table, the names would be in the rows, and the notes in the columns, my idea is this.

1 answer

2


You can create an array of objects, where each object stores the student’s name + the 4 notes, in this format (the values are hypothetical):

notas = [
   {nome: "aluno1", nota1: 2, nota2: 4, nota3: 5, nota4: 9}
   ...
]

It works that way:

var notas = [];

for (let i = 1; i <= 3; i++) {
   let aluno = prompt('NOME DO ALUNO: ');
    notas.push({nome: aluno});
    for (let y = 1; y < 5; y++) {
        notas[i-1]["nota"+y] = Number(prompt(`${y}ºBIMESTRE: `));
    }
}

To scroll through this format (object array):

var notas = [];

for (let i = 1; i <= 3; i++) {
   let aluno = prompt('NOME DO ALUNO: ');
    notas.push({nome: aluno});
    for (let y = 1; y < 5; y++) {
        notas[i-1]["nota"+y] = Number(prompt(`${y}ºBIMESTRE: `));
    }
}

// percorrer

notas.forEach(function(e){
   
   let texto = `<strong>Aluno:</strong> ${e.nome}<br>
   Nota 1: ${e["nota"+1]}<br>
   Nota 2: ${e["nota"+2]}<br>
   Nota 3: ${e["nota"+3]}<br>
   Nota 4: ${e["nota"+4]}<br>
   `;
   
   document.write(texto);
   
});


Or if you want to create arrays in this format:

notas = [
   ["aluno1", 1, 2, 3, 4]
   ...
]

Where the index [0] of the subarrays is the name of the student and the subsequent indexes are the grades:

var notas = [];

for (let i = 1; i <= 3; i++) {
   let aluno = [prompt('NOME DO ALUNO: ')];
    notas.push(aluno);
    for (let y = 1; y < 5; y++) {
        notas[i-1].push(Number(prompt(`${y}ºBIMESTRE: `)));
    }
}

To go through this format (array of arrays):

var notas = [];

for (let i = 1; i <= 3; i++) {
   let aluno = [prompt('NOME DO ALUNO: ')];
    notas.push(aluno);
    for (let y = 1; y < 5; y++) {
        notas[i-1].push(Number(prompt(`${y}ºBIMESTRE: `)));
    }
}

// percorrer

notas.forEach(function(e){
   
   let texto = `<strong>Aluno:</strong> ${e[0]}<br>
   Nota 1: ${e[1]}<br>
   Nota 2: ${e[2]}<br>
   Nota 3: ${e[3]}<br>
   Nota 4: ${e[4]}<br>
   `;
   
   document.write(texto);
   
});

Browser other questions tagged

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