简体   繁体   English

未捕获的类型错误:未定义不是函数

[英]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. 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:如果由于.push()方法而导致错误来自这一行:

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() .然后,问题是asteroids尚未初始化为数组,因此它没有方法.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.如果未定义Asteroid构造函数,也可能会出现此类错误。

Is the Asteroid function defined?是否定义了Asteroid函数?

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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