JS - 显示与该分数相关的最高分数和名称

时间:2014-03-17 02:37:06

标签: javascript arrays

High score fiddle

JS代码:

var names = ["Ben", "Joel", "Judy", "Anne"];
var scores = [88, 98, 77, 88];
var textDisplay;

var $ = function (id) {
    return document.getElementById(id);
};


var listArray = function () {
    var scoresString = "";
    for (var i = 0; i < names.length; i++) {
        scoresString += names[i] + ", " + scores[i] + "\n";
    } // lists all names and scores in their respective array orders
    $("results").value = scoresString;

};

var showBest = function () {
    var bestString = "";
    var highScore = Math.max.apply(Math, scores);
    for (var i in scores) {
        if (scores[i] > highScore) highScore = scores[i];
        bestString += "High Score Student = " + names[i] + "\n" + "High Score = " + highScore;
    }
    $("results").value = bestString;
};

    $("add").onclick = addElement;
    $("name").focus();
    $("list_array").onclick = listArray;
    $("show_best").onclick = showBest;

&#34;显示最佳分数&#34;按钮应显示得分最高的学生姓名及其得分。现在,它显示了最高分,但它也将该分数与数组中的所有名称相关联,因此所有名称都显示相同的高分。我只想要与最高分相关的名字(1个名字,1个分数)。

非常感谢任何输入!

编辑:我的问题是var showBest - 如何只显示一个名称和一个分数?现在它显示所有名称和一个高分。

1 个答案:

答案 0 :(得分:1)

你走在正确的轨道上:

var highScore = Math.max.apply(Math, scores);     // gives the highest score
var scoreIndex = scores.indexOf(highScore);       // gives the location of the highest score
var bestStudent = names[scoreIndex];              // gets the name at the same location
var bestString += "High Score Student = " + bestStudent + "\n" + "High Score = " + highScore;

此代码假设2个数组的顺序正确。