Cerpin Taxt Cerpin Taxt - 3 months ago 7
Javascript Question

Having problems when using objects passed through an array

I have a public 'bullets' array that I'm pushing a private bullet object into. It has x and y properties and I want to change it's y property so that every time I press the space key it creates a bullet object, pushes it into the bullets array and then calls a function that loops through the array and updates each bullet's y property.

However, every time I press the space key I get an error:

Uncaught TypeError: Cannot read property 'y' of undefined

This is slightly beyond my understanding and I'm not sure how I can write this so that the bullet objects in the bullets array are not 'undefined'.

If anyone has any suggestions I would greatly appreciate the help.

//called every frame
function playGame()
{
movePlayer();
playerShoot();
moveBullet();
}

//PLAYER SHOOT FUNCTION
//If the space key is down, player.shoot is true and the bullet object is created.

function playerShoot()
{
if(player.shoot)
{
var bullet = Object.create(spriteObject);
bullet.width = 16;
bullet.height = 16;
bullet.x = (player.width - bullet.width) / 2;
bullet.y = (player.height - bullet.height) / 2;
bullets.push(bullet);
player.shoot = false;
}
}

//MOVING THE BULLET
function moveBullet()
{
if(bullets.length !== 0)
{
for(var i = 0; i <= bullets.length; i++)
{
var bullet = bullets[i];
console.log("bullet: " + bullet);

//bullet.y causes error: Uncaught TypeError: Cannot read property 'y' of undefined

if((bullet.y + bullet.height) >= 0)
{
bullet.y--;
}
else
{
bullets.splice[i, 0];
}
}
}
}

//RENDERING THE BULLETS
function renderBullet()
{
if(bullets.length !== 0)
{
for(var i = 0; i <= bullets.length; i++)
{
var bullet = bullets[i];
bullet.render();
}
}
}

Joy Joy
Answer

Here:

for(var i = 0; i <= bullets.length; i++)

Should be replaced with:

for(var i = 0; i < bullets.length; i++)

In your code, the last iteration gets bullets[bullets.length], which is undefined. So comes the error.

This error:

Uncaught TypeError: Cannot read property 'y' of undefined

Indicates that the object is undefined, so cannot access the property y on it. So always make sure your object is defined before accessing properties on it.

Comments