Relatively simple, for example: there is an area
, and now it is required to delete all nodes in it. I believe many people will write like this:
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 correct, traverse one by one, and finally delete them all. However, if you think about it carefully, every time a node is deleted, controlinfo.length will become smaller. If this continues, all nodes cannot be deleted - there is a bug. So how to improve? It is already very clear, since starting from the beginning is not possible, then we will start from the end, which is completely correct, as follows:
var divpanel = document.getElementById("newbody");
var controlinfo= divpanel.childNodes;
for(var index = controlinfo.length - 1;index > = 0 ;index--)
{
divpanel.removeChild(controlinfo[index]);
}
Debugging, Very Good!
This kind of trap is not only encountered in JavaScript, basically all languages, such as C#, Java, etc., we will encounter such problems, and sometimes we will waste a lot of time because of such problems. . I have known about this problem for a long time, but I always trust my memory too much and fail to record it properly. Now I record it to warn myself and share it with everyone.