So when writing a game on Khan Academy When I try to remove a bullet from the array I run into the error "Object does not support method splice" I have been checking my code for hours and have not found out why it does not work. Ideas?
EDIT: The code used to remove a bullet is bullets[i].splice(i,1);
and that is what errors out my code.
MVCE:
var bullets = [];
var bullet= function(x,y,blah)
{
//code that is not important here
};
bullets.push(bullet(0,0,30));
for(var I = 0; I < bullets.length; I++){
if(bulletRemove){
bullets[I].splice(i,1)
}
}
You have a variable named bullets
:
var bullets = [];
(Side note: Why is there a random curly bracket right before this line?)
This bullets
variable is an array. It holds instances of the Bullet
class:
bullets.push(new Bullet(x, y, 10, player.x+bSize/2, player.y+bSize/2));
You can use the array to access a Bullet
at a particular index, and then you can call functions of the Bullet
class on that instance:
bullets[i].move();
You can also call the splice()
function on the array itself:
bullets.splice(i,1);
However, you can't call the splice()
function on a particular Bullet
instance!
bullets[i].splice(i,1);
This line is taking an instance of Bullet
from the i
index of the bullets
array, and then trying to call the splice()
function from the Bullet
class. But the Bullet
class doesn't have a splice()
function! This is what's causing the error.
Instead, you probably meant to call it on the array itself:
bullets.splice(i,1);
In the future, please please please try to narrow your problem down before posting a question. Try to post an MCVE instead of your entire project. You could have put together an example program that used just a few lines to create a hard-coded array and used that to demonstrate your problem. Chances are you would have found the problem yourself in the process of creating the MCVE!