简体   繁体   English

错误:无法读取未定义的属性“nota”。 (Javascript)

[英]Error: Cannot read the property 'nota' of undefined. (Javascript)

Can you help me with this error: "Cannot read the property 'nota' of undefined. "你能帮我解决这个错误吗:“无法读取未定义的属性'nota'。”

 const arrayN = [ {nome: "Rapha", nota: 10}, {nome: "Renan", nota: 8}, {nome: "Stefani", nota: 12} ]; function maiorNota(alunos) { // Encontrando a maior nota no vetor turma. let maior = []; for (let i = 0; i < alunos.length; i++) { if (alunos[i].nota > alunos[i+1].nota || alunos[i].nota > maior) { maior = alunos[i]; } } return maior; } const melhor = maiorNota(arrayN) console.log(melhor)

Missleading Error误导性错误

So the error is a bit missleading, but you should be aware when you do comparison with indice +1 because it could be that you try to access an element which is not existing .所以这个错误有点误导,但是当你与indice +1进行比较时你应该知道,因为它可能是你试图访问一个不存在的元素。

In Java for example this would throw an index out of bounds exception which says more then "Cannot read property 'nota' of undefined".例如,在Java中,这将引发一个索引越界异常,该异常比“无法读取未定义的属性'nota'”更多。

Solution解决方案

If you would like to do a comparison with the next element then one solution is to update your condition in the for-loop and don't run to the end of the array instead run to the end-1 of the array.如果您想与下一个元素进行比较,那么一种解决方案是在 for 循环中更新您的条件,不要运行到数组的末尾,而是运行到数组的 end-1。

In your last iteration step then you do the comparison with element at i with element at position i+1.在最后一个迭代步骤中,您将 i 处的元素与 position i+1 处的元素进行比较。

 const arrayN = [{ nome: "Rapha", nota: 10 }, { nome: "Renan", nota: 8 }, { nome: "Stefani", nota: 12 } ]; function maiorNota(alunos) { // Encontrando a maior nota no vetor turma. let maior = []; for (let i = 0; i < alunos.length - 1; i++) { if (alunos[i].nota > alunos[i + 1].nota || alunos[i].nota > maior) { maior = alunos[i]; } } return maior; } const melhor = maiorNota(arrayN) console.log(melhor)

You reached an index that does not exist.您到达了一个不存在的索引。 You need to verify it exists.您需要验证它是否存在。

const arrayN = [
    { nome: "Rapha", nota: 10 },
    { nome: "Renan", nota: 8 },
    { nome: "Stefani", nota: 12 }
];

function maiorNota(alunos) {
    // Encontrando a maior nota no vetor turma.
    let maior = [];
    for (let i = 0; i < alunos.length; i++) {
        if (alunos[i] && alunos[i].nota) > (alunos[i + 1] && alunos[i + 1].nota) || (alunos[i] && alunos[i].nota > maior) {
            maior = alunos[i];
        }
    } return maior;
}
const melhor = maiorNota(arrayN)

console.log(melhor)

When you get to last iteration i +1 is going to be 3, and there is no 3 index, so it is undefined.当您进行最后一次迭代时,i +1 将是 3,并且没有 3 索引,因此它是未定义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM