How to return values with numbers in an array

Asked

Viewed 769 times

5

I’m trying to perform a school grade calculation with Javascript but the result returns me NaN.

Code:

array_notas = [10, 9, 8, 7]

function calcularMedia(param) {
    for (let i = 0; i <= 4; i++) {
        var result = 0;
        result += param[i].value;
    }

        let media = result / 4

        if (media < 6)
            console.log(`Aluno reprovado! MÉDIA DO ALUNO => ${media}`)
        else {
            console.log(`Aluno aprovado! MÉDIA DO ALUNO => ${media} `)
        }
};

console.log(calcularMedia(array_notas))

2 answers

7


The indexes of an array start at zero. So if an array has 4 elements, the indexes go from 0 to 3. But in the for you put i <= 4, then it will try to access index 4, which does not exist, so first it must change the condition to < instead of <=. And in fact, the ideal is to use length, that takes the size of the array, so you don’t need to use fixed values, and the code works for arrays of any size (if you always use 4 and the array has more elements, it won’t take all, and if the array has fewer elements, it will try to access elements that don’t exist; in both cases the result will be wrong).

Another detail is that if the array contains numbers, just do param[indice] to take its value. You do not need the attribute value (this attribute is used when you take the value of a input HTML, but in your case the array contains numbers, so you don’t need the value).

In addition, the result = 0 should stay before the for. Putting him inside the for, you Zera the value every hour, and the end result is not the sum of the notes.

Finally, the function is not returning anything (it prints the result and does not return any value), so there is no need to do console.log in the result of this (if you notice, your code prints a undefined further, which is the result of printing the non-existent return of the function). In fact I would change the function to return the value of the average, and whoever calls the function does what you want with the result.

Then it would look like this:

let array_notas = [10, 9, 8, 7];

function calcularMedia(param) {
    let result = 0; // zera a variável antes do for, e não dentro dele
    for (let i = 0; i < param.length; i++) { // use param.length
        result += param[i]; // não use value
    }

    return result / param.length; // só retorne o valor e pronto
}

let media = calcularMedia(array_notas); // aqui você pega o retorno e faz o que quiser com ele
if (media < 6) {
    console.log(`Aluno reprovado! MÉDIA DO ALUNO => ${media}`);
} else {
    console.log(`Aluno aprovado! MÉDIA DO ALUNO => ${media} `);
}

I also put a semicolon at the end of the lines (and removed one that was unnecessary after the } that closes the function). It may seem "freshness", but I created this habit to avoid some bizarre situations which may occur if you do not use semicolons on all lines (see more on the subject here).

1

You are trying to access an array value that does not exist (index [4]) in making i <= 4. With this is returning undefined, and trying to add undefined with some value will result in NaN.

Change to i < 4 or i < param.length (array size, if the array has variable size).

Now, the var result = 0; should stay out of the loop, otherwise it will be zeroed at all times.

array_notas = [10, 9, 8, 7];

function calcularMedia(param) {
   var result = 0;
   for (let i = 0; i < 4; i++) {
      result += param[i];
   }
   let media = result / 4
   
   if (media < 6)
      console.log(`Aluno reprovado! MÉDIA DO ALUNO => ${media}`)
   else {
      console.log(`Aluno aprovado! MÉDIA DO ALUNO => ${media} `)
   }
};

console.log(calcularMedia(array_notas))

Browser other questions tagged

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