这是我项目的代码:
' _'是一种选择器方法。
'更新'运行间隔为0.1
'初始化'创造了
'球'是我试图创造的对象
' ball.set()'是不起作用的方法。
var width = window.innerWidth/3;
var height = window.innerHeight-60;
var balls = [];
var id;
function rand(min, max) {
return (Math.random() * (max - min)) + min;
}
function run(){
init();
}
function init(){
document.write("<div style='width:"+width+"px;height:"+height+"px;' id='container'></div>");
new Ball(width/2-12.5, height/2-12.5, rand(-2, 2), rand(-2, 2), 1);
id = setInterval(update, 0.1);
}
function _(elem){
return document.getElementById(elem);
}
function update(){
for(var b in balls){
b.set();
}
}
function Ball(x, y, vx, vy, ind){
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.ind = ind;
balls[this.ind] = this;
_("container").innerHTML+=("<div style='top:"+y+"px;left:"+x+"px;' class='ball' id='ball"+this.ind+"'></div>");
this.deleteBall = function () {
_('ball'+this.ind).outerHTML = "";
balls[this.ind] = null;
};
this.set = function(){
this.x += this.vx;
this.y += this.vy;
var elem = _("ball"+this.ind);
elem.style.left = this.x + 'px';
elem.style.top = this.y + 'px';
};
}
run();
我试图为我正在制作的JS游戏制作一个Ball对象。唯一的问题是Google Chrome给我一个错误:
Uncaught TypeError: b.set is not a function
at update (ballgame.js:29)
update @ ballgame.js:29
我做错了什么?
答案 0 :(得分:0)
我不知道完整的要求,但我找到了这个问题的原因。问题在于行
var tasks = urls.Select(i => httpClient.GetAsync(i)).ToArray();
await Task.WhenAll(tasks);
假设第一次使用'ind'值为5调用构造函数。这将设置balls [5] =此对象。现在'球'阵列长度变为6,球[0]通过球[4]将包含值'未定义'。
现在在'update'方法中,当你遍历ball数组时,由于ball [0]到ball [4]未定义,你会得到错误
balls[this.ind] = this;