javascript - What happen when a value of an Array is Erased while Looping? -


i asking self : what happens emplacement of array if erased done while looping array ?

suppose you've got bunch of elements arranged in array.

now suppose you've got multiple identical elements , want erase them.

you're doing classical double loop , when element found duplicated erase it...

what happen array in case ? element after take place of erased element ? element take null value ?

here schema better comprehension (sorry i'm far artist :) )

enter image description here

exemple of code in javascript :

arraycity = $.makearray($('.cityname')); for(i=0; < arraycity.length;i++) {     for(j=0; j < arraycity.length; j++)     {         if (arraycity[i].innerhtml == arraycity[j].innerhtml)         {             arraycity.splice(j, 1);         }     } } 

and continue on it; i've been told better in case iterate in reverse. in case incomprehension bigger; happens if erase, lets say, first index of array ? push whole array ? in case happens first loop .. ?

here second schema illustrate second part of question (as ugly first :/ i'm afraid )

enter image description here

i'll glad have bit of explanation on case. thank reading !

when delete element array of following elements shifted down 1 index. looping through array in reverse can prevent skipping elements. example if have array [1, 2, 3] , delete item @ index 0 array [2, 3]. step index 1 , miss item 2 (now @ index 0). if need make sure hit every element can try looping in reverse or using array.proto.foreach().


Comments