javascriptforeachundefined

for iteration, element is undefined


I have this code:

for(var i in this.units)
 {
 if(this.units[i].x==att.x && this.units[i].y==att.y){}
 //... some more code
 }

and sometimes, randomly, I get an error this.units[i] is undefined.

Anybody got any idea how this is possible?


Solution

  • Pointy briefly touched upon the probable cause of the issue in his answer and that is that this.units[i] could be null. If you try and access a property on a null value you will get an "is null or not an object" error. In your example this is thrown by the attempt to access this.units[i].x in the if statement. The safest thing to do is to check and see if it's a null value first:

    for(var i in this.units) 
    { 
        if (this.units[i] === null)
            continue;
    
        if(this.units[i].x==att.x && this.units[i].y==att.y){} 
        //... some more code 
    }
    

    You should also check out the other points of his answer, most importantly that for...in loops aren't ideal for arrays.