This question deals with the case where you're using an index variable for iteration.
But does anyone know what happens when you are using a JS for ... of
iteration and decide to remove elements from it in the course of the loop? As it happens I'm using a JS Set. But I presume the answer, whatever it is, would apply to a simple array as well... In Java you are not allowed to do this: it would produce a ConcurrentModificationException
.
I.e.:
const nodes = new Set();
...
for( node of nodes ){
if( node.tagName === 'BR' ){
nodes.delete( node );
}
}
... in short can I be sure that JS would take the above code "in its stride" and would be guaranteed not to fail to iterate through any nodes, or conversely complain about some internal index variable being "out of range"?
NB there is also the case where you delete not the element you are currently processing, but another element which you find to be another member of the Set
, e.g. in this case, if you found that node.parentNode
was in the Set
and you then deleted it. Quite surprised at the down votes here. This is not an obvious question and presumably involves intimate knowledge of JS algorithms.
NB2 I have tested it... and it seems to work OK. But that is not proof that it will always work OK.