2016-03-03 68 views
2

我一直在做一些關於freecodecamp的練習,我被困在這個循環練習的嵌套上。我能找到解決方案,但我不太明白。嵌套for循環多維數組。概念

有人可以向我解釋變量J的第二個循環是如何工作的?我已經在網上閱讀說第一個for循環是用於外部數組,第二個是內部數組,但爲什麼停在兩個for循環,爲什麼不是三個?

function multiplyAll(arr) { 
    var product = 1; 

    // Only change code below this line 

    for (var i=0;i<arr.length;i++) { 
     for (var j=0;j<arr[i].length;j++) { 
      product *= arr[i][j]; 
     } 
    } 

    // Only change code above this line 
    return product; 
} 

// Modify values below to test your code 
multiplyAll([[1,2],[3,4],[5,6,7]]); 
+0

因爲'內部數組'的長度= 2 ..並且循環條件小於長度,所以它將迭代索引=> 0 ... 1 ...中斷... – Rayon

+1

您可以使用調試器爲line在每一次迭代中記下「i」和「j」的值,或者我建議你自己用筆或紙做一次。 –

+0

因爲數組嵌套到二級。 – 2016-04-09 11:33:27

回答

7

這是非常基本的邏輯問題。理解這一點的理想方式是@Abhinav在評論中提到的方式。在瀏覽器控制檯

// Module that multiplies all the number in 2D array and returns the product 
function multiplyAll(arr) { 
    var product = 1; 

    // Iterates the outer array 
    for (var i=0;i<arr.length;i++) { 
     // 1st Iter: [1,2] 
     // 2nd Itr: [3,4] 
     // 3rd Itr: [5,6,7] 
     console.log('i: ' + i, arr[i]); 
     for (var j=0;j<arr[i].length;j++) { 
      // Outer loop 1st inner 1st : 1 
      // Outer loop 1st inner 2nd : 2 
      // Outer loop 2nd inner 1st : 3 
      // ... 
      console.log('j: ' + j, arr[i][j]); 

      // Save the multiplication result 

      // Prev multiplication result * current no; 
      // Outer loop 1st inner 1st : 1 * 1 = 1 
      // Outer loop 1st inner 2nd : 1 * 2 = 2 
      // Outer loop 2nd inner 1st : 2 * 3 = 6 
      // Outer loop 2nd inner 1st : 6 * 4 = 24 
      // ... 
      product *= arr[i][j]; 
     } 
    } 

    // Only change code above this line 
    return product; 
} 


multiplyAll([[1,2],[3,4],[5,6,7]]); 

運行此。這可能會給你一些清晰。

+0

感謝您的回答!現在變得更有意義了。 – Stev

+0

您是由您製作的「i」還是「j」,或者字符串在這種情況下如何工作?我不明白爲什麼不用「a」或「b」等詞 – nelruk