Reputation: 3
Hi everyone I'm currently a student working on a project out of my book, here is the code I am having the issue with.
for (var i = 0; i < numAsteroids; i++) {
var radius = 5+(Math.random()*10);
var x = canvasWidth+radius+Math.floor(Math.random()*canvasWidth);
var y = Math.floor(Math.random()*canvasHeight);
var vX = -5-(Math.random()*5);
asteroids.push(new Asteroid(x, y, radius, vX));***<---line 21***
};
Now when I run this is keeps telling me I have an:
Uncaught TypeError: undefined is not a function line 21.
But I have the code exactly how it is in my book that's what I don't understand. If anyone could help me with this problem it would be great!
Upvotes: 0
Views: 1240
Reputation: 2259
Is the Asteroid
function defined?
The following works.
var asteroids = [],
numAsteroids = 10,
canvasWidth = 10,
canvasHeight = 10,
radius = 10;
for (var i = 0; i < numAsteroids; i++) {
var radius = 5+(Math.random()*10);
var x = canvasWidth+radius+Math.floor(Math.random()*canvasWidth);
var y = Math.floor(Math.random()*canvasHeight);
var vX = -5-(Math.random()*5);
asteroids.push(new Asteroid(x, y, radius, vX));
};
// Is the Asteroid function/class defined?
function Asteroid(x, y, r, vX) {
}
Upvotes: 0
Reputation: 707328
If the error is coming from this line because of the .push()
method:
asteroids.push(new Asteroid(x, y, radius, vX));
Then, the issue is that asteroids
has not been initialized as an array so thus it doesn't have a method .push()
.
You can initialize it like this:
var asteroids = [];
for (var i = 0; i < numAsteroids; i++) {
var radius = 5+(Math.random()*10);
var x = canvasWidth+radius+Math.floor(Math.random()*canvasWidth);
var y = Math.floor(Math.random()*canvasHeight);
var vX = -5-(Math.random()*5);
asteroids.push(new Asteroid(x, y, radius, vX));
}
It might also be possible to get this type of error if the Asteroid
constructor function is not defined.
Upvotes: 2