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

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

你能帮我解决这个错误吗: “无法读取未定义的 属性 '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)

您访问了一个不存在的索引。您需要验证它是否存在。

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)

误导性错误

所以错误有点误导,但是当你与 indice +1 进行比较时你应该注意,因为你可能试图访问一个元素 不存在.

Java 中,例如,这将抛出一个 索引越界异常 ,它说的更多然后是“无法读取 属性 'nota' 的未定义".

解决方案

如果您想与下一个元素进行比较,那么一个解决方案是在 for 循环中更新您的条件,而不是 运行 数组的末尾 运行数组的 end-1.

然后在最后一个迭代步骤中,将 i 处的元素与位置 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)

当你到达最后一次迭代时 i +1 将是 3,并且没有 3 索引,因此它是未定义的。