samedi 1 octobre 2016

For loop with two counters, and confusing if-else statements.(JavaScript)

<!doctype html>
<html>
  <head>
    <script>
      function do_something() {
        var theBody = document.getElementsByTagName("body")[0];
        var theImg = document.createElement("img");
        theImg.src = "cat.png";
        theBody.appendChild(theImg.cloneNode(true));
        var count = 0;
        for (var i = 0; i < 10; i++, count++) {
            if (i == 5) continue;
            if (count == 3) {
                count = 0;
                theBody.removeChild(theBody.lastChild);
            } else {
                theBody.appendChild(theImg.cloneNode(true));
            }
            if (i > 7) break;
        }
      }
    </script>
  </head>
  <body onload="do_something()"></body>
</html>

I am supposed to tell how many images would a modern browser display.

I have two major doubts here:

  • When i=4, what is the value of count? I think it would be 0, but don't why I am confused about it.
  • As the code tells, when count = 0, an image will be removed from the body. Does the code append an image, and then remove an image? Or, does it simply remove one image? This is the part that is confusing because nothing is said about what happens when i=3.

According to the given answer, 6 images are added in the loop, and 2 are removed. So, a total number of 5 images are displayed.

Aucun commentaire:

Enregistrer un commentaire