简体   繁体   中英

Uncaught TypeError: undefined is not a function

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!

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.

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) {

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM