Kiy*_*ana 6 javascript arrays iteration for-loop
此问题的目的是迭代列表,找到列表中的最大值,然后报告最高值的索引值.我能够使用两个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);
Run Code Online (Sandbox Code Playgroud)
我最初尝试使用一个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);
Run Code Online (Sandbox Code Playgroud)
我不知道如何解决添加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(", "));Run Code Online (Sandbox Code Playgroud)
<!-- 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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
290 次 |
| 最近记录: |