2016-03-03 63 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