简体   繁体   中英

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()

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! (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. You want i < taskDetails.length .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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