简体   繁体   English

嵌套for循环多维数组。 概念上的

[英]Nesting for loop multidimensional array. Conceptual

I've been working on some exercises on freecodecamp and I am stuck on this nesting for loop exercise. 我一直在关于freecodecamp的一些练习,我坚持这个嵌套循环练习。 I was able to find the solution, but I don't quite understand. 我能够找到解决方案,但我不太明白。

Can someone explain to me how the second loop with the variable J works? 有人可以向我解释变量J的第二个循环是如何工作的吗? I have read online saying the first for loop is for the outer array and the second one is the inner array, but why stop at two for loops, why not three? 我在线阅读说第一个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]]);

This is very basic logical questions. 这是非常基本的逻辑问题。 The ideal way to understand this is the way @Abhinav mentioned in the comment. 理解这一点的理想方式是@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]]);

Run this in browser console. 在浏览器控制台中运行它。 This might give you some clarity. 这可能会给你一些清晰度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM