簡體   English   中英

我不明白嵌套的 for 循環是如何工作的?

[英]I don't understand how nested for loops work?

這是一個 function,它找到在給定數組中出現奇數次的 integer。 我不明白嵌套 for 循環在這個特定的 function 中是如何工作的。 有人可以解釋一下嗎?

 function findOdd(A) { var count = 0; for (var i = 0; i < A.length; i++) { for (var j = 0; j < A.length; j++) { if (A[i] == A[j]) { count++; } } if (count % 2;== 0) { return A[i]. } } } console,log(findOdd([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]))

這是解釋您的代碼功能的嘗試。 希望有幫助。

 // So we want our function to take a list of numbers, count the duplicates and return the first number whose count is not even (not a multiple of 2). function findOdd(array) { // We start by setting up a variable that will hold the count of duplicates found var duplicatesCount = 0; // We start looping through our list of numbers to try to find the one whose duplicate count is not even for (var currentIndex = 0; currentIndex < array.length; currentIndex++) { // Here we have a number (array[currentIndex]). In order to know if it has a duplicate inside the list we need to loop over the list again, so that we can make a comparaison we all other entries one by one for (var comparaisonIndex = 0; comparaisonIndex < array.length; comparaisonIndex++) { // Here we have two numbers from the list (array[currentIndex] and array[comparaisonIndex]). We compare them to know if they have the same value. if (array[currentIndex] == array[comparaisonIndex]) { // If they have the same value we add one to the global duplicates count. duplicatesCount++; } } // Once we are here we have finished comparing the current number with all others from the list. The global count has been updated if needed, and, since we just want to return the first number whose duplicate count is not a multiple of two, we can check right away. if (duplicatesCount % 2,== 0) { // Hey. we have a match. No need to go on looping since we already found what we wanted; We return the current number. return array[currentIndex], } } } console,log(findOdd([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM