JS -显示最高分数和与该分数相关联的名称
JS - Show highest score and name associated with that score
高分小提琴
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;
这段代码假设这两个数组的顺序合适。
相关文章:
- 单击时显示关联数组的元素
- 关联数组 - 使用图像滑块显示键值
- 如何在创建后立即显示关联模型的特性
- 显示关联阵列中所有元素的键和值
- 检查是否显示与当前视图模型关联的 DOM
- 使用ajax和grails显示所选值中的关联数据库值
- CSS/Javascript-Do“;显示:无”;暂时删除任何关联的事件侦听器
- 显示与单独控制器关联的模型
- 在将json编码的关联数组从php传递到javascript时显示错误
- jQuery表行切换显示/隐藏关联按钮
- PHP会话中显示关联数组
- 尝试在fanybox中创建两个仅显示与其关联的照片的图库
- 显示另一个HTML页面上图像(alt)的文本关联
- Meteor JS:RegisterHelper,用于显示关联的用户信息
- 使用html在html表中显示JavaScript关联数组
- 如何显示hasMany关联
- 如何在表中显示关联数组
- 使用d3.js显示表中关联数组的数据
- JS -显示最高分数和与该分数相关联的名称
- 显示与动态创建的缩略图相关联的正确图片