[英]JavaScript For Loop Array Iteration Issue - Using One vs Two Loops
此問題的目的是遍歷列表,在列表中找到最大值,然后報告最高值的索引值。 我能夠使用兩個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
迭代(當然,你應該知道它們的存在,它們可以被用來循環),並學習使用JavaScript與函數式編程范式( 一很棒的交互式教程 ),因為它可以使代碼更具可讀性,並且不易出錯。
解決問題的方法可以使用[].reduce()
:
function highest(numbers) {
return numbers.reduce(function(winner, current, index) {
if (current > winner.value) {
return {value: current, indices: [index]};
} else if (current === winner.value) {
winner.indices.push(index);
return winner;
} else {
return winner;
}
}, {value: Number.NEGATIVE_INFINITY, indices: []});
}
function highest(numbers) { return numbers.reduce(function(winner, current, index) { if (current > winner.value) { return {value: current, indices: [index]}; } else if (current === winner.value) { winner.indices.push(index); return winner; } else { return winner; } }, {value: Number.NEGATIVE_INFINITY, indices: []}); } document.querySelector('button').addEventListener('click', function() { var randoms = new Array(100).join(' ').split('').map(function() {return Math.ceil(Math.random() * 100)}); document.querySelector('#array').innerHTML = JSON.stringify(randoms); document.querySelector('#result').innerHTML = JSON.stringify(highest(randoms)); });
<button>run</button> <h3>the array</h3> <pre id="array"></pre> <h3>the result</h3> <pre id="result"></pre>
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];
//clone array keeping original as scores, sort the new cloned array, grab the max value
var highscore = scores.slice(0).sort()[scores.length - 1];
var highscoreSolutions = [];
//find occurances of highscore and push to array
for (var i = 0; i < scores.length; i++){
if (scores[i] == highscore){
highscoreSolutions.push(i);
}
}
alert('highscore: ' + highscore + '\nindexes: ' + highscoreSolutions)
您可以使用Array.slice(0)克隆陣列
然后運行sort()並通過檢查長度-1來獲取新排序數組的最后一個值
然后迭代循環以找到高分所在的索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.