How to show a value from array that relates to the value of another array, javascript

后端 未结 6 1166
轻奢々
轻奢々 2021-01-28 19:39

I am trying to have the name show up with the score that relates to that name. So if the highest score is 98 I want Joels name to show up in the display where is says name here.

6条回答
  •  Happy的楠姐
    2021-01-28 20:13

    You can store the index instead of the highest score and use it to get the name. I have changed your code to support it and added comment 'Changes' to wherever the changes are,

     var names = ["Ben", "Joel", "Judy", "Anne"];
        var scores = [88, 98, 77, 88];
        var average;
        var total = 0;
        var highScoreIndex = 0;// Changes
    
        var $ = function (id) { return document.getElementById(id); };
    
        var displayResults = function () {
            for (var i = 0; i < scores.length; i++) {
                    total = total + scores[i];       //both are numbers so adds
                        if (scores[i] > highestScore) {
                    highestScoreIndex = i; // Changes
                }
    
               }
    
        //then calculate the average and display
                average = parseInt(total/scores.length);
                document.getElementById("results_header").innerHTML =   
         ("Results");
                document.getElementById("results").innerHTML = ("\nAverage score  
              is " + average + "\nHigh score = " + names[highestScoreIndex] + " with a score of " +    
            scores[highestScoreIndex]); //Changes
    
    
        };
    
        window.onload = function () {
            //$("add").onclick = addScore;
            $("display_results").onclick = displayResults;
            //$("display_scores").onclick = displayScores;
        };
    

提交回复
热议问题