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

JS - Show highest score and name associated with that score

本文关键字:关联 显示 最高分 JS      更新时间:2023-09-26

高分小提琴

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;

"显示最佳成绩"按钮应显示得分最高的学生姓名及其分数。现在,它显示的是最高分,但它也将这个分数与数组中的所有名字联系起来所以所有名字显示的都是相同的最高分。我只想要与最高分相关联的名称(1个名称,1个分数)。

任何输入将不胜感激!

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

你做对了:

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;

这段代码假设这两个数组的顺序合适。