这个问题的目标是遍历一个列表,找到列表中最大的值,然后报告最高值的索引值。我能够使用两个for循环解决这个问题:
var scores = [60, 50, 58, 54, 54, 58, 50, 52, 54, 48, 69, 34, 55, 51, 52, 44, 51, 69, 64, 66, 55, 52, 44, 18, 41, 53, 55, 61, 51, 44];
var highscore = 0;
var highscoreSolutions = [];
for (var i = 0; i < scores.length; i++){
if (scores[i] > highscore){
highscore = scores[i];
}
}
for (var i = 0; i < scores.length; i++){
if (scores[i] == highscore){
highscoreSolutions.push(i);
}
}
console.log(highscore);
console.log(highscoreSolutions);
我最初尝试使用一个for循环来解决这个问题,但我遇到了一些初始化问题,即无论如何,第一个索引值都会被包含在最高分数列表中:
var scores = [60, 50, 58, 54, 54, 58, 50, 52, 54, 48, 69, 34, 55, 51, 52, 44, 51, 69, 64, 66, 55, 52, 44, 18, 41, 53, 55, 61, 51, 44];
var highscore = 0;
var highscoreSolutions = [];
for (var i = 0; i < scores.length; i++){
if (scores[i] >= highscore){
highscore = scores[i];
highscoreSolutions.push(i);
}
}
console.log(highscore);
console.log(highscoreSolutions);
我不确定如何解决添加0索引值的问题(没有使用两个单独的for循环)。有人能帮我吗?非常感谢!:)
highscore = score[0]
和highscoreSolutions = [0]
开始,而不是从0
开始。 - T.J. CrowderhighestSolutions = [i]
应该改为highscoreSolutions = [i]
。 - Kiyana