Having problems with the for loop, not repeating too much

So, I have a problem with this FOR loop, which I just cannot understand. In this case, I know that this must be repeated at least twice. An array at least looks something like this:

dTrackerArray = {sParentValue, 1234, sParentValue, 5678} 

But for some reason, this for loop only removes one instance instead of all of them.

  var check = $.inArray(sParentValue, dTrackerArray); if (check != -1) { for(var i = dTrackerArray.length; i > 0; i--) { if( dTrackerArray[i] === sParentValue ) { dTrackerArray.splice(i,1); dTrackerArray.splice(i-1,1); } }} 

I really appreciate any help I can get here! Thanks!

EDIT: 2nd splicing - remove 1234 "connected" using sParentValue. It seems to be working fine.

+4
source share
3 answers

The problem is in the loop. you start with: var i = dTrackerArray.length and accept dTrackerArray[i] , this element does not exist. Moreover, you forgot to interact with the index element 0. Therefore, you need to change the for loop to:

 for(var i = dTrackerArray.length-1; i >= 0; i--) 
+4
source

Easy to miss, but you need i >= 0 .

EDIT: Although I think your main problem is that you modify the array during the loop. Obviously, with my correction you will get an error outside the boundaries of the second splice.

 var check = $.inArray(sParentValue, dTrackerArray); if (check != -1) { for(var i = dTrackerArray.length; i >= 0; i--) { if( dTrackerArray[i] === sParentValue ) { dTrackerArray.splice(i,1); dTrackerArray.splice(i-1,1); //when i == 0 then exception } }} 

Since you know the format of the array, you can do this with a while loop:

 var check = $.inArray(sParentValue, dTrackerArray); while(check > -1) { dTrackerArray.splice(check,1); check = $.inArray(sParentValue, dTrackerArray); } 
+1
source

Have you already gone through this with a debugger? This is probably all you need to do to understand what is happening here. I would add this to the comment, but I do not have these privileges yet.

0
source

All Articles