javascript item splice self out of list

Assuming the bad guy knows what list he's in, why not?

BadGuy.prototype.die = function()
{
    activeEnemies.splice(activeEnemies.indexOf(this), 1);
}

By the way, for older browsers to use indexOf on Arrays, you'll need to add it manually.


The way you would do it is as follows:

var game_state = { active_enemies: [] };
function Enemy() {
    // Various enemy-specific things go here
}
Enemy.prototype.remove = function() {
    // NOTE: indexOf is not supported in all browsers (IE < 8 most importantly)
    // You will probably either want to use a shim like es5-shim.js
    // or a utility belt like Underscore.js
    var i = game_state.active_enemies.indexOf(this);
    game_state.active_enemies.splice(i, 1);
}

See:

  • Es5-Shim
  • Underscore.js

Notta bene: There are a couple of issues here with this manner of handling game state. Make sure you are consistent (i.e. don't have enemies remove themselves from the list of active enemies, but heroes remove enemies from the map). It will also make things more difficult to comprehend as the code gets more complex (your Enemy not only is an in-game enemy, but also a map state manager, but it's probably not the only map state manager. When you want to make changes to how you manage map state, you want to make sure that code is structured in such a way that you only need to change it in one place [preferably]).