mardi 2 février 2021

I could not find the sum of numbers in the array although I used for loop in JavaScript

    var score_list = [];
    var score_length = score_list.length;
    // var i;
    function enter_score( ){
        document.getElementById("score_msg").innerHTML = "You enter: "+document.getElementById("new_score").value;
        score_list.push(document.getElementById("new_score").value);
    }
    function display_all( ){
        document.getElementById("all_scores_list").innerHTML = "You have entered these scores:"+ score_list.join(",");
    }
    var total = 0;
    function calculate( ){
        for (var i = 0; i<score_length;i++){
            total += Number(score_list[i]);
        }
        // console.log(score_list);
        // console.log(total);
        document.getElementById("total_score").innerHTML = "The total input score is: "+total;
    }

For this program, I would like to find the sum of the numbers in the array score_list, but when I used total += Number(score_list[i]) then when I clicked the button the result is still 0. May I ask where should I fix the problem in order to have total to be the sum of the numbers in the array score_list?




Aucun commentaire:

Enregistrer un commentaire