繁体   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