I have an itch to scratch

Hi,
There something small that is bothering me.

In the tutorial on creating entities there is this code

for (i = 0; i < this.entities.length; i++) {
        this.entities[i].timer -= dt;
        if (this.entities[i].timer < 0) {
            // entity.destroy() deletes all components and removes Entity from the hierarchy
            this.entities[i].entity.destroy();

            // Remove from the local list
            this.entities.splice(i, 1);
        }
    }

Ok, now this works fine in practice but I do wonder if it is working as the programmer is expecting. I draw your attention to the fact that the value being tested “this.entities.length” in the “for” parameters is being altered by “this.entities.splice(i,1)” so the test doesn’t actually test all entities in the first pass only in subsequent “updates” does it complete.

Here is a clearer example of what I mean.

 this.entities = [1,2,3,4];
    console.log(this.entities.length);
    for (i = 0; i < this.entities.length; i++) {
            // Remove from the local list
            this.entities.splice(i, 1);
        
    }
    console.log('finished);
    console.log(this.entities.length);

now if you run this in an initialize routine you will find it produces

4
finished
2

and the left over entities are 2 and 4

now back to the original example , if you imagine that the first two entities have expired timers then only one of the entities will be removed on the first pass as after the splice the second entity is occupying the index of the deleted one but the counter has moved on.

So that’s my itch scratched :wink:

If you need to iterate through an array and modify same array, then this construction might help:

var i = this.entities.length;

while(i--) {
    if (this.entities[i].timer < 0) {
        this.entities[i].entity.destroy();
        this.entities.splice(i, 1);
    }
}
1 Like