0

So I'm making a simple html5 Canvas game for educational purposes. I have an array which holds all of the separate prototypes of the same enemy object. When the enemy goes off the screen or perhaps is killed by player, I want to be able to despawn it from within the object by deleting it altogether from the array. I'll probably create new instances of the enemy by pushing a new object to the array with some pseudo-random properties.

I apologize for not providing code, if you'd like to see anything specific just ask.

1 Answers1

1

You can use Array.prototype.splice, which takes two argumets index, howMany to remove elements from an array, starting at the specified index

Heres a basic example

var players = [1,2,3,4,5,6]
players.splice (3,1); //remove 1 element beginning at index 3
console.log (players) // [1,2,3,5,6]

As you see player 4 (which is at index 3 in players) got removed

Moritz Roessler
  • 8,542
  • 26
  • 51
  • How do I figure out where any one object is indexed in the array from within that object? –  Aug 19 '13 at 19:09
  • @AlexKrokos `players.indexOf (player)` – Moritz Roessler Aug 19 '13 at 19:40
  • Every element of the array is a prototype of the same object, how can I use indexOf if theyr'e all the same? –  Aug 20 '13 at 00:08
  • @AlexKrokos What do you mean by "Every element of the array is a prototype of the same object" ? An object has only one prototype, multiple objects can have the same prototype, but not the other way round. Do you mean every element has the same prototype? / is an instance of player ? – Moritz Roessler Aug 20 '13 at 07:22