0

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
2
  • You may use a for(const taskDetail of taskDetails) loop to prevent such typos Commented Oct 22, 2017 at 9:19
  • That syntax is very helpful... thanks! Commented Oct 23, 2017 at 7:37

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Oops! Silly me :P
0

Change the condition of the loop to i < taskDetails.length

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.