Daniel Oliveira Daniel Oliveira - 3 months ago 11
Javascript Question

Javascript delete does not removed the desired property

I am using nodejs to create a game. It happens that this time I am not able to use Delete. It is not working and I have no idea why.

I execute this line:

delete Bullet.list[i]


And
Bullet.list
is an object with properties and after executing this line, the desired property is not removed.

Here is my code (you can see the above line of code in context here below):

var Map = require("./Map.js")
var Player = require("./Player.js");
var Bullet = require("./Bullet.js");
var Fly = require("./Fly.js");
var Settings = require("./Settings.js");

var Simulation = function(SOCKET_LIST){

//Update Bullets
for(var i in Bullet.list){
var bullet = Bullet.list[i];
bullet.update();

var shooter = Player.list[bullet.parent];
//Bullets collide with flies
for(var i in Fly.list){
var fly = Fly.list[i];
if(!bullet.toRemove && bullet.getDistance(fly) < 15){
if(shooter){
shooter.updateCoins(fly.killCoins);
shooter.updateXp(fly.killXp);
}
bullet.toRemove = true;
fly.toRemove = true;
}
}
//Collide with player
for(var i in Player.list){
var player = Player.list[i];
if(player.death) continue;
if(!bullet.toRemove && bullet.getDistance(player) < 32 && shooter !== player.id && shooter.team != player.team && !player.immune){
player.hp -= 1;
player.hpChanged = true;
if(player.hp <= 0){
if(shooter)
player.kill(shooter);
else
player.kill();
}
bullet.toRemove = true;
}
}
//Collide with map
if(typeof shooter == "undefined" || shooter.shootsCollideMap && Map.isColliding(bullet))
bullet.toRemove = true;

//Remove bullets
if(bullet.toRemove){
delete Bullet.list[i]; /*HERE IS THE PROBLEM. THE PROPERTY IS NOT BEING DELETED*/
Bullet.removePack.push[bullet.id];
}

}


I am not able to delete the property "i" from the object Bullet.list.

Answer

Your three for loops are all sharing the same variable i and thus you aren't deleting the i index you want to. This is because var i is function scoped, not scoped to the individual for loop.

When you do this:

delete Bullet.list[i];

The value of i is whatever i is after your previous for loop and probably not the item you actually want to delete. Perhaps you mean to break out of the for loop previously so that i will be a specific item you want to remove?

Or you need to separately save to another variable an index of an item that you want to remove. Or, just remove an item inside the for loop when the value of i is current.

Remember that var is function scoped. So both your var i declarations in your two nested for loops are actually referencing the exact same variable, not declaring a new one. I would recommend changing the name of the loop index in one of the two loops to be a separate variable.

If you are running in an environment where let is fully supported, you could use let i instead of var i and then the value of i would be uniquely scoped to only the for loop in which it was declared.

Comments