gpt4 book ai didi

JavaScript For 循环数组迭代问题 - 使用一个循环与两个循环

转载 作者:数据小太阳 更新时间:2023-10-29 05:25:47 25 4
gpt4 key购买 nike

这个问题的目的是遍历一个列表,找到列表中的最大值,然后报告最大值的索引值。我能够使用两个 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 循环)。谁能帮我吗?非常感谢!! :)

最佳答案

当你找到一个新的最高值时,你需要清除列表:

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 = [];
var score;

for (var i = 0; i < scores.length; i++) {
score = scores[i];
if (score == highscore) {
highscore = score;
highscoreSolutions.push(i);
} else if (score > highscore) {
highscore = score;
// We have a new highest score, so all the values currently in the array
// need to be removed
highscoreSolutions = [i];
}
}

snippet.log(highscore);
snippet.log(highscoreSolutions.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

关于JavaScript For 循环数组迭代问题 - 使用一个循环与两个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32105681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com