gpt4 book ai didi

javascript - 无法修复 "Uncaught TypeError: Cannot read property ' 0' of undefined"

转载 作者:行者123 更新时间:2023-12-03 06:25:05 25 4
gpt4 key购买 nike

我有 4 个图像数组,如下所示:

car_image_left = new Image();
car_image_left.src = 'img/car2_left.png';
car_image_mid_left = new Image();
car_image_mid_left.src = 'img/car2_mid_left.png';
car_image_mid_right = new Image();
car_image_mid_right.src = 'img/car2_mid_right.png';
car_image_right = new Image();
car_image_right.src = 'img/car2_right.png';

car_image = [car_image_left,car_image_mid_left,car_image_mid_right,car_image_right];

它们都在这个数组中:

images = [car_image, truck_image, hole_image, banana_image];

我的绘图功能遇到问题:

for (i = 0; i < obstacles.length; i++){
this.context.drawImage(obstacles[i].images[obstacles[i].id][obstacles[i].lane-1],
obstacles[i].pos_x - obstacles[i].width/2,
obstacles[i].pos_y - obstacles[i].height/2,
obstacles[i].width,
obstacles[i].height);
}

所以,基本上 Obstacles 是一个数组,我在其中存储所有对象,但它们都是不同的,除了每个对象都有一个 ID。

这是一个类的示例:

function Car(lane) {
this.id = 0;
this.lane = lane;
this.height = 108.75;
this.width = 99;
this.pos_x = CENTER;
this.pos_y = -350;
this.car_image = images[this.id][this.lane-1];
}

最佳答案

索引超出范围,你会得到未定义的,我认为这是一行:

this.car_image = images[this.id][this.lane-1];

作为解决方案,将其放在该行之前,您应该了解到底出了什么问题:

console.log(images.length);
console.log(this.id);
console.log(images[this.id]);
console.log(images[this.id].length);
console.log(this.lane-1);

通过比较长度和索引,您应该看到哪个超出范围。

关于javascript - 无法修复 "Uncaught TypeError: Cannot read property ' 0' of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38694396/

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