relentless-coder
relentless-coder

Reputation: 1546

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:

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.

Upvotes: 0

Views: 96

Answers (1)

Ben Wainwright
Ben Wainwright

Reputation: 4651

When i=4, what is the value of count? I think it would be 0, but don't why I am confused about it.

When i == 3, count is set to 0. At the end of the for block, count++ is executed, so by the time i == 4, count == 1

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.

  • i == 0 append
  • i == 1 append
  • i == 2 append
  • i == 3 image from previous step removed
  • i == 4 append

etc.

Upvotes: 1

Related Questions