我正在研究如何从数组中返回最高分数的索引,但我正在努力弄清楚是否可以从该方法返回多个项目,或者我是否需要使用返回数组中两个最高分数的索引的替代方法。
var scores = [60, 50, 60, 58, 54, 54,
58, 50, 52, 54, 48, 69,
34, 55, 51, 52, 44, 51,
69, 64, 66, 55, 52, 61,
46, 31, 57, 52, 44, 18,
41, 53, 55, 61, 51, 44];
var tests = scores.length;
var highest;
for (var i = 0; i < scores.length; i++) {
if (i === 0) {
highest = scores[i];
}
if (scores[i] > highest) {
highest = scores[i];
}
}
最佳答案
返回包含索引的数组。当你得到一个高于最高的元素时,清空数组并将 i 放入其中。当你得到一个等于最高的元素时,将 i 插入数组。
var highest = scores[0];
var indexes = [0];
for (var i = 1; i < scores.length; i++) {
if (scores[i] > highest) {
// Found new highest, reset everything
indexes = [i];
highest = scores[i];
} else if (scores[i] == highest) {
// Found duplicate highest, add its index to indexes array
indexes.push(i);
}
}
关于javascript - 多个最高分的返回索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33112213/