For iteration, the undefined element

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, by chance, I get this.units [i] undefined error.

Has anyone understood how this is possible?

+3
source share
5 answers

Explain briefly touched on the probable cause of the problem in his answer, and this means that it this.units[i]can be zero. If you try to access the property by a null value, you will get a "null or not object" error. In your example, this is done by trying to access the this.units[i].xif statement. The safest thing to do is check and see if this is null 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 
}

, , for...in .

+1

for (var i in this.units)

, "units". , , - - :

this.units.balloon = null;

"in" , , . , - . ( !)

+2

MY Bad: , python!

, - :

del this.units[i]

- - . No-No.

+1

, , "i" , prop key, , , .

-, , , . . , , ,

obj.myProp = null;

, for for - . ,

delete obj.myProp;

myProp for in.

+1
for(var i = 0; i < this.units.length; i++){
    if(this.units[i].x==att.x && this.units[i].y==att.y){}
}

this.units this.units. for ( ).

0

Source: https://habr.com/ru/post/1736120/


All Articles