简体   繁体   中英

Understanding basic javascript logic

I am currently working on learning/practicing DOM manipulation and ran across this tutorial/practice sheet.

https://github.com/lmuntaner/dom_manipulation

I am currently confused on the loop created by the createGrid function. ... The function "createGrid" is created and takes an argument. The function creates a for loop which has another loop nested inside of it... that has the same exact statements as the first one... Why create a separate loop? Why not just have one for loop? Can someone explain this too me? (The guy who wrote this code is far beyond me, but i still would like to understand why)

    $(function () {
  var rows = 10;
  var cols = 10;
  var cells = [];
  function createGrid(root) {
    for(var i = 0; i < cols; i++) {
      for(var j = 0; j < cols; j++) {
        var cell = $('<div>').addClass('cell');
        cells.push(cell);
        root.append(cell);
      }
    }
  };

  var updateState = function() {
    cells.forEach(function (cell) {
      var randomNum = Math.random() * 2;
      if (randomNum > 1) {
        cell.addClass('active');
      } else {
        cell.removeClass('active');
      }
    });
  }

  setInterval(updateState, 500);

  var $root = $('.container');
  createGrid($root);
});

Well, actually I'm pretty sure that's a mistake from the developer. As you think, that has not sense. Just change the father loop like this:

function createGrid(root) {
    for(var i = 0; i < rows; i++) {
        for(var j = 0; j < cols; j++) {
            var cell = $('<div>').addClass('cell');
            cells.push(cell);
            root.append(cell);
        }
    }
}

Because the common way of create a table or grid, is make rows with the father loop, and the columns with the nested loop. He just didn't realize his mistake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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