gpt4 book ai didi

javascript - 错误 : Cannot read the property 'nota' of undefined.(Javascript)

转载 作者:行者123 更新时间:2023-12-02 02:26:42 25 4
gpt4 key购买 nike

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

最佳答案

误导性错误

所以这个错误有点误导,但是当您与索引+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)

关于javascript - 错误 : Cannot read the property 'nota' of undefined.(Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65540063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com