Understanding nested for loops in javascript

前端 未结 7 1431
梦毁少年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:28

    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.

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

    // 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

提交回复
热议问题