Understanding nested for loops in javascript

前端 未结 7 1515
梦毁少年i
梦毁少年i 2021-01-30 09:39

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

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


        
7条回答
  •  时光取名叫无心
    2021-01-30 10:19

    The double for loop you have above works like so:

     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]

    Hope that makes sense!

提交回复
热议问题