javascript - 带有两个计数器的 For 循环,以及令人困惑的 if-else 语句。(JavaScript)

标签 javascript if-statement for-loop

<!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=4 时,count 的值是多少?我认为它会是 0,但不知道为什么我对此感到困惑。
  • 正如代码所示,当 count = 0 时,图像将从正文中删除。代码是否附加图像,然后删除图像?或者,它只是删除一张图像吗?这是令人困惑的部分,因为没有提及 i=3 时会发生什么。

根据给定的答案,循环中添加了 6 张图像,并删除了 2 张图像。因此,总共显示 5 张图像。

最佳答案

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

i == 3时,count设置为0。在for block 的末尾,count++ 被执行,所以当 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 追加
  • i == 1 追加
  • i == 2 追加
  • i == 3 已删除上一步中的图像
  • i == 4 追加

等等

关于javascript - 带有两个计数器的 For 循环,以及令人困惑的 if-else 语句。(JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39806631/

相关文章:

javascript - 如何使用 Node JS 连接到外部 websocket?

javascript - 在 Dreamhost VPS 上安装 Node.js

c - IF - Else 语句不起作用

javascript - 塞萨尔解密。如何处理非字母数字字符 | JS

datetime - 带时间戳的批处理 For 循环

java - 为什么这个 Java 循环不终止?

javascript - jQuery缩略图替换方法(需要添加A标签的解决方案)

javascript - getJSON函数中覆盖的变量值

javascript - 为什么我的 IF 语句不适用于时间?

javascript - 我很难从计算机接收任何输出。滥用变量?或者我的 If 语句有问题?