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