简体   繁体   English

无法读取对象数组中最后一个对象的属性(javascript)

[英]Unable to read an attribute of last object in array of objects (javascript)

I am working on a basic prototype of rating based to-do app in javascript. 我正在使用基于评分的待办事项应用程序的基本原型。 There's an object which I am using to store task name and its rating. 我正在使用一个对象来存储任务名称及其等级。 Example: 例:

taskDetails = [
    {name: "C", rating: 69.3425},
    {name: "A", rating: 60.93875},
    {name: "D", rating: 57.32,
    {name: "B", rating: 59.795}
]

And then there's a function checkAllEqual() 然后是一个函数checkAllEqual()

var checkAllEqual = function(){
    var flag = true;
    var temp = [];    
    for(var i = 0; taskDetails.length; i++){
        if(taskDetails[i].rating){     //Line no. 58 of the code
            var rating = taskDetails[i].rating;
            temp.push(parseInt(rating.toFixed(2)));
        }
    }

    console.log(temp);
    return flag;
}

This function checks if all the todos have equal ratings or not. 此功能检查所有待办事项是否具有相同的评级。 It works fine until 3 iterations but in the last one throws an error that 'rating' is undefined even when 'rating' inside if parenthesis holds correct value! 它可以正常工作直到3次迭代,但在最后一次迭代中会抛出一个错误,即使括号内的值正确,即使在内部的“评级”中,“评级”也未定义! (Checked in the debugger) (在调试器中检查)

I couldn't find the reason. 我找不到原因。 Please help. 请帮忙。

The error: 错误:

app.js:58 Uncaught TypeError: Cannot read property 'rating' of undefined
    at checkAllEqual (app.js:58)
    at <anonymous>:1:1

Your loop condition is just taskDetails.length , so that's an infinite loop that runs right off the end of your array. 您的循环条件只是taskDetails.length ,因此这是一个无限循环,从数组末尾开始运行。 You want i < taskDetails.length . 您要i < taskDetails.length

将循环条件更改为i < taskDetails.length

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

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