gpt4 book ai didi

javascript - 数组类型错误

转载 作者:行者123 更新时间:2023-12-01 02:47:52 25 4
gpt4 key购买 nike

所以我收到了“未捕获的类型错误:无法读取未定义的属性'0'” at update”第 42 行,就是这个:

init.ctx.moveTo(this.trail[0].x,this.trail[0].y); 

来自以下代码:

window.onresize = function(){
init.canvas.width = window.innerWidth;
init.canvas.height = window.innerHeight;
//updateComponents();
}
var init = {
canvas: new Object(),
ctx: new Object(),
constructCanvas: function(){
this.canvas = document.getElementById("canvas");
this.ctx = this.canvas.getContext("2d");
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}
}
init.constructCanvas();

var background = {
color: "green",
refresh: function(){
init.ctx.fillStyle = this.color;
init.ctx.fillRect(0,0,init.canvas.width,init.canvas.height);
}
}
//background.refresh();

function updateComponents(){
background.refresh();
}

function WalkingLine(arguments){
this.frames = 0;
this.trail = [];
this.walkLength = 5;
this.position = arguments.position;
this.color = "black";
this.trail[0] = this.position;
}
WalkingLine.prototype = {
update: function(){
init.ctx.beginPath();
init.ctx.moveTo(this.trail[0].x,this.trail[0].y);
var i;
for(i=1;i<this.trail.length;i++)
init.ctx.lineTo(this.trail[i].x,this.trail[i].y);
init.ctx.stroke();
this.generateNext();
},
genarateNext: function(){
this.trail[this.trail.length] = {x:this.trail[this.trail.length-1].x+5,y:this.trail[this.trail.length-1].y};
init.ctx.lineTo(this.trail[this.trail.length-1].x,this.trail[this.trail.length-1].y);
inti.ctx.stroke();
}
};
var one = new WalkingLine({position:{x:100,y:100}});
setTimeout(one.update,1000);

所以我不明白为什么我显然试图访问数组中的无效索引,因为我在 WalkingLine 类的构造函数中显式设置了 table[0],但尽管它仍然说它是未捕获的类型错误。

最佳答案

你失去了上下文:

setTimeout(one.update,1000);

这样你只传递update而不传递one,所以当稍后调用它时,它不知道它属于哪里。您需要直接调用它(在箭头函数内):

setTimeout(()=>one.update(),1000);

或者您需要将函数绑定(bind)到一个:

setTimeout(one.update.bind(one),1000);

关于javascript - 数组类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47142508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com