[Chartjs]-My for loop does not iterate in Javascript

4πŸ‘

its because you use the same variable i for each loop, use it with different increments [i,j,z] here

$(document).ready(function(){
    $.getJSON("/rest/BatchService/batches", function(json)
    {
        //json.length = 2, json is an arraylist of jsonobjects
        for(var i = 0; i < json.length; i++){
            //get batchid
            batchid = json[i]["batch"]["batch_id"];
            //put batchids into an option tag and put it in select tag
            var option=$('<option />').val(json[i]["batch"]["batch_id"]).text("Batch " +json[i]["batch"]["batch_id"]);
            $("#dropdownBatches").append(option);

            //get from 'questions' the name and marks and put the variables in a chart
            var questions = json[i]["batch"]["questions"];
            for(var j in questions){
                var name= questions[j]["name"];
                chartjslabels.push(name);
                console.log(name);

                var marks = questions[j]["mark"];
                var sum = 0;
                for(var z = 0; z < marks.length; z++){
                    sum+= parseInt(marks[z]);
                }
                var avg = sum/marks.length;
                chartjsdata.push(avg);
            }
        }

1πŸ‘

You are using the same variable i ,Change the inner loop to something else

       for(var j in questions){
            var name= questions[j]["name"];
            chartjslabels.push(name);
            console.log(name);

            var marks = questions[j]["mark"];
            var sum = 0;
            for(var k = 0; i < marks.length; i++){
                sum+= parseInt(marks[k]);
            }
            var avg = sum/marks.length;
            chartjsdata.push(avg);
        }

1πŸ‘

The problem here is very simple, you are using the i variable in 3 nested for loops, so its value gets incremented several times, causing the parent for loop to run only once.

0πŸ‘

 for(var i in questions){

       for(var i = 0; i < marks.length; i++){

using i for both loops is causing the behaviour you are seeing.

0πŸ‘

You cannot use the same variable name in nested for-loops. This means the i-var will be incremented in all the loops, meaning the code will not be executed as you want it to.

Change the variable names to other letters to fix your problems.

Leave a comment