Javascript 理解javascript中的嵌套for循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36413159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:01:42  来源:igfitidea点击:

Understanding nested for loops in javascript

javascriptfor-loop

提问by stellatores

I'm learning JavaScript at the moment on freecodecamp and they have an example for nested for loops in one of their excercises:

我目前正在 freecodecamp 上学习 JavaScript,他们的一个练习中有一个嵌套 for 循环的示例:

 var arr = [[1,2], [3,4], [5,6]];
 for (var i=0; i < arr.length; i++) {
  for (var j=0; j < arr[i].length; j++) {
    console.log(arr[i][j]);
  }
}

With console.log = 1 2 3 4 5 6 undefined.

使用 console.log = 1 2 3 4 5 6 未定义。

I understand for loops more or less, and I understand that [i] and [j] are used to access the array (I think?). I just don't understand why at the end it just prints out those numbers? I found this question asked a few years back but it just explains how to write them, not how they work:

我或多或少了解 for 循环,并且我了解 [i] 和 [j] 用于访问数组(我认为?)。我只是不明白为什么最后它只打印出这些数字?几年前我发现这个问题被问到,但它只是解释了如何编写它们,而不是它们是如何工作的:

For loop in multidimensional javascript array

多维javascript数组中的for循环

I broke it down into:

我把它分解成:

var arr = [  [1,2], [3,4], [5,6]];for (var i=0; i < arr.length; i++) {
 console.log(arr[i]);}

Which prints out

哪个打印出来

[ 1, 2 ]
[ 3, 4 ]
[ 5, 6 ]
undefined

and

var arr = [  [1,2], [3,4], [5,6]];
for (var i=0; i < arr.length; i++) {  
 for (var j=0; j < arr[i].length; j++) {    
  console.log(arr[i]);  }}

which prints out:

打印出来:

[ 1, 2 ]
[ 1, 2 ]
[ 3, 4 ]
[ 3, 4 ]
[ 5, 6 ]
[ 5, 6 ]
undefined

and

var arr = [  [1,2], [3,4], [5,6]];
 for (var i=0; i < arr.length; i++) {  
  for (var j=0; j < arr[i].length; j++) {    
   console.log(arr[j]);  }}

which prints out

打印出来

[ 1, 2 ]
[ 3, 4 ]
[ 1, 2 ]
[ 3, 4 ]
[ 1, 2 ]
[ 3, 4 ]
undefined

I understand the first two arr[i]. The loop iterates through the array and prints out the individual elements (in this case an array) and in the second one I guess it just does it twice because there are two loops. What I don't understand is:

我理解前两个arr[i]。循环遍历数组并打印出单个元素(在本例中为数组),在第二个中我猜它只执行两次,因为有两个循环。我不明白的是:

  1. why the last array in arr[j] is not printed out (where did the [5, 6] go?)
  2. why arr[i][j] suddenly eliminates the arrays and just prints out the numbers
  3. where the 'undefined' comes from
  1. 为什么 arr[j] 中的最后一个数组没有打印出来([5, 6] 去哪里了?)
  2. 为什么 arr[i][j] 突然消除了数组并只打印出数字
  3. “未定义”来自哪里

Could anyone help me out with this and explain the steps the code takes before printing it out in the console? I would really like to understand it but don't even know how to search for this question the right way.

任何人都可以帮我解决这个问题并解释代码在控制台中打印之前所采取的步骤吗?我真的很想理解它,但甚至不知道如何以正确的方式搜索这个问题。

采纳答案by Gremash

var arr = [[1,2], [3,4], [5,6]];

This is an array of arrays. It is a little bit easier to read like this:

这是一个数组数组。像这样阅读会更容易一些:

var arr = [
            [1,2],
            [3,4],
            [5,6]
          ];

That makes it a little bit easier to see that you have an array of 3 arrays. The outer 'for' will loop through each of 1st level arrays. So the very first outer for loop when i=0 you are going to grab the first inner array [1,2]:

这使得更容易看到您有一个由 3 个数组组成的数组。外部“for”将循环遍历每个第一级数组。因此,当 i=0 时,第一个外部 for 循环将获取第一个内部数组 [1,2]:

for (var i=0; i < arr.length; i++) {
    //First time through i=0 so arr[i]=[1,2];
}

In the inner loop you are going to loop through each of the 3 inner arrays one at a time.

在内部循环中,您将一次遍历 3 个内部数组中的每一个。

for (var j=0; j < arr[i].length; j++) {
    //Handle inner array.
}

This argument grabs the length of the inner array:

此参数获取内部数组的长度:

arr[i].length

So on your first time through the outer loop i=0 and arr[i] is going to equal [1,2] because you are grabbing the 0th element. Remember, arrays elements are always counted starting at 0, not 1.

因此,在您第一次通过外循环时, i=0 并且 arr[i] 将等于 [1,2],因为您正在抓取第 0 个元素。请记住,数组元素始终从 0 开始计数,而不是从 1 开始。

Finally you are printing out the results with:

最后,您将打印出结果:

console.log(arr[i][j]);

The first time through you can break it down a little. i=0 and j=0. arr[0][0] which translates as grab the first element from the outer array and then the first element from the first inner array. In this case it is '1':

第一次通过你可以把它分解一点。i=0 和 j=0。arr[0][0] 转换为从外部数组中获取第一个元素,然后从第一个内部数组中获取第一个元素。在这种情况下,它是“1”:

[
    [1,2], <-- 0
    [3,4], <-- 1
    [5,6]  <-- 2
];

The code will loop through the first first set [1,2], then the second [3,4], and so on.

代码将循环遍历第一个第一个集合 [1,2],然后是第二个 [3,4],依此类推。

回答by omarjmh

The double for loop you have above works like so:

上面的双 for 循环的工作原理如下:

 var arr = [[1,2], [3,4], [5,6]];

 for (var i=0; i < arr.length; i++) {
  // i = 0, then we loop below:
  for (var j=0; j < arr[i].length; j++) {
    //here we loop through the array which is in the main array
    //in the first case, i = 0, j = 1, then we loop again, i = 0, j = 1
    console.log(arr[i][j]);
    //after we finish the stuff in the 'j' loop we go back to the 'i' loop 
    //and here i = 1, then we go down again, i, remains at 1, and j = 0, then j = 1
    //....rinse and repeat, 
  }
}

In plain english:

简单的英语:

We grab the first element in the main array, which is an array itself, we loop through that, and log at each index, this is terminated by our length condition in the second loop. We then move to to the next index of the main array, which is an array itself.... and so on, until we reach the end of the main array

我们获取主数组中的第一个元素,它是一个数组本身,我们遍历它,并记录每个索引,这在第二个循环中由我们的长度条件终止。然后我们移动到主数组的下一个索引,它是一个数组本身......等等,直到我们到达主数组的末尾

To access and index in the main array, we need to use array[i]- that index holds an array - so to go INTO that array, we need to use array[i][j]

要访问和索引主数组,我们需要使用array[i]- 该索引保存一个数组 - 所以要进入该数组,我们需要使用array[i][j]

Hope that makes sense!

希望这是有道理的!

回答by upgrd

Despite some caveatsof using for-in loops on arrays, they can imo sometimes help to clear the mess in nested loops a bit:

尽管在数组上使用 for-in 循环有一些注意事项,但它们有时可以帮助清除嵌套循环中的混乱:

var arr = [[1,2], [3,4],[5,6]];

for (i in arr){
      for (j in arr[i]){
        console.log(arr[i][j]);
      }
    }

Also code visualizationcan clarify execution!

另外代码可视化可以明确的执行!

回答by Dan Levy

I know this is an old question... But because this is a popular post from ye olde google search, I feel it's helpful to add a way to visualize what's going on in nested for-loops.

我知道这是一个老问题......但是因为这是来自ye olde google search的热门帖子,我觉得添加一种方法来可视化嵌套 for 循环中发生的事情会很有帮助。

As a JS teacher, I've found this method super helpful for visually-oriented people and those w/ dyslexia and related things).

作为一名 JS 老师,我发现这种方法对以视觉为导向的人和有阅读障碍和相关事物的人非常有帮助)。

// Original: https://repl.it/@justsml/nested-loop-visualizations
var nums = [[1,2,3], [4,5,6], [7,8,9]];

console.log('Example w/ Numbers:\n');
console.log('The array data: ', JSON.stringify(nums));

for (var i=0; i < nums.length; i++) {
  // Main/"top" array - accessing via "arr[i]"
  for (var j=0; j < nums[i].length; j++) {
    // here we loop through the "child" arrays
    let helpfulLabel = `nums[${i}][${j}]`
    let value = nums[i][j]
    console.log(helpfulLabel, 'Value=' + value);
  }
}

console.log('\nExample w/ String Data:\n');
var letters = [['a', 'b', 'c'], ['d', 'e', 'f'], ['x', 'y', 'z']];
console.log('The array data: ', JSON.stringify(letters));

for (var i=0; i < letters.length; i++) {
  for (var j=0; j < letters[i].length; j++) {
    let helpfulLabel = `letters[${i}][${j}]`
    let value = letters[i][j]
    console.log(helpfulLabel, 'Value=' + value);
  }
}

Preview of Results

结果预览

repl results

复制结果

回答by Tayyab Siddiqui

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];
       console.log(product)
     }
   }
   // Only change code above this line
   return product;
 }
 // Modify values below to test your code
 multiplyAll([[1], [2], [3]])
 //multiplyAll([[1, 2], [3, 4], [5, 6, 7]]);
 //multiplyAll([[5, 1], [0.2, 4, 0.5], [3, 9]])

回答by samin

function multiply(arr) {
    var product = 1;

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

    return product;
}

回答by vadi taslim

  1. why the last array in arr[j] is not printed out (where did the [5, 6] go?)
  1. 为什么 arr[j] 中的最后一个数组没有打印出来([5, 6] 去哪里了?)

You may notice that if you print out jas console.log(j), it will print 6 times as 0, 1, 0, 1, 0, 1. And what you're trying to print is arr[j]which [5, 6]will not be displayed because its on arr[2]

您可能会注意到,如果您打印jconsole.log(j),它将打印 6 次为0, 1, 0, 1, 0, 1。您尝试打印的arr[j]内容[5, 6]将不会显示,因为它已打开 arr[2]

  1. why arr[i][j] suddenly eliminates the arrays and just prints out the numbers
  1. 为什么 arr[i][j] 突然消除了数组并只打印出数字

As you state there, arris an array of 3 arrays. arr[i]represents 3 arrays either of [1, 2], [3, 4]or [5, 6]. And the jin arr[i][j]represents the index of those 3 arrays. This is called Multidimensional Array. arr[i][j]does not eliminate the array, but It selects the value in the index of jinside arr[i].

正如您所说,arr是一个由 3 个数组组成的数组。arr[i]表示任一的3个阵列[1, 2][3, 4][5, 6]。而jin arr[i][j]代表这 3 个数组的索引。这称为 多维数组arr[i][j]不消除数组,而是选择jinside的索引中的值arr[i]

  1. where the 'undefined' comes from
  1. “未定义”来自哪里

It's just chrome thingy when you use console.log. Chrome returns undefined whenever you try to do that. Try to do it on firefox and you will see it no longer.

当您使用console.log. 每当您尝试这样做时,Chrome 都会返回 undefined。尝试在 Firefox 上执行此操作,您将不再看到它。