For example, if you have a region <div id = "newbody"> </div>, delete all nodes. I believe many people will write like this:
Copy codeThe Code is as follows:
Var divpanel = document. getElementById ("newbody ");
Var controlinfo = divpanel. childNodes;
For (var index = 0; index <controlinfo. length; index ++)
{
Divpanel. removeChild (controlinfo [index]);
}
At first glance, yes, yes. This is very correct. traverse one by one and delete all at last. However, when you delete a node, the value of controlinfo. length will decrease. In this case, you cannot delete all nodes. A Bug exists. So how can we improve it? It is clear that starting from the beginning does not work, so we Start from the end, which is completely correct, as shown below:
Copy codeThe Code is as follows:
Var divpanel = document. getElementById ("newbody ");
Var controlinfo = divpanel. childNodes;
For (var index = controlinfo. length-1; index> = 0; index --)
{
Divpanel. removeChild (controlinfo [index]);
}
Debug, Very Good!
This kind of trap is not only encountered in JavaScript. Basically all languages, such as C # and Java, will encounter such problems, sometimes time is wasted due to such problems. I have known this problem for a long time, but I always believe in my memory, but I have not recorded it well. Now I want to record it, warn myself, and share it with you.