[英]Javascript for loop behaving strange
I have a for
loop to loop through the node which is <ul>
that has 5 <li>
elements. 我有一个
for
循环来循环通过具有5个<li>
元素的<ul>
节点。 I am trying to create a div
for each of those li
elements 我正在尝试为每个
li
元素创建一个div
When I try to append the li
elements to div
then the for loop is behaving strange 当我尝试将
li
元素附加到div
,for循环表现出奇怪
for (var i = 0; i < docNodes.children.length; i++) {
var docs = document.createElement('div');
docs.appendChild(docNodes.children[i]); //If this line is removed then it loops 5 times else it loops only 3 times
}
Could someone let me know what is wrong with the code 有人可以让我知道代码有什么问题吗
The behavior isn't that weird. 行为不是那么奇怪。 You're changing the length of
docNodes.children
in every iteration of the loop. 您需要在循环的每次迭代中更改
docNodes.children
的长度。 For the next iteration, it checks the length again: 对于下一次迭代,它将再次检查长度:
i | Length | i < length
0 5 true
1 4 true
2 3 true
3 2 false // Loop stops before the 4th iteration.
The reason the length is changing, is because docs.appendChild
actually removes the target element from it's previous parent. 长度改变的原因是因为
docs.appendChild
实际上从其先前的父级中删除了目标元素。
A way to work around this issue, it to iterate over the children in the opposite order: 解决此问题的一种方法,它以相反的顺序遍历子级:
for (var i = docNodes.children.length - 1; i >= 0 ; i--) {
var docs = document.createElement('div');
docs.appendChild(docNodes.children[i]);
}
i | Length | i >= 0
4 5 true
3 4 true
2 3 true
1 2 true
0 1 true
-1 0 false // Loop stops before the 6th iteration.
As other point out you modify the length of the array during the loop. 另外要指出的是,您可以在循环期间修改数组的长度。 In JavaScript it's better to use Array.prototype.forEach instead of an old fashioned for loop.
在JavaScript中,最好使用Array.prototype.forEach而不是老式的for循环。
For example: 例如:
docNodes.children.forEach(function (child) {
var docs = document.createElement('div');
docs.appendChild(child);
});
Try this. 尝试这个。 And apply similar logic into your code.
并将类似的逻辑应用于您的代码。
<div id="list"></div>
<script>
let children = ['1','2','3','4','5'];
for (var i = 0; i < children.length; i++) {
var node = document.createElement("LI");
var textnode = document.createTextNode(children[i]);
node.appendChild(textnode);
document.getElementById("list").appendChild(node);
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.