gpt4 book ai didi

JavaScript myObject 有时未定义

转载 作者:行者123 更新时间:2023-11-28 09:26:09 25 4
gpt4 key购买 nike

您好,我在 JavaScript 中遇到了一些问题。虽然我浏览了一些以前的帖子,但我还没有找到答案。

我正在开发一个 HTML5+Javascript 游戏,其中有一个情感对象:情感Img是一个Image(),类型是一个字符串。

function Emotion(emotionImg, type) {

this.emotionImg = emotionImg;
this.emotionImg.onload = function() {
console.log("added emotion: "+type);
};
this.type = type;

// last emotion of a scene
this.isLast = false;

this.setLast = function() {
this.isLast = true;
};

return this;

}

这些情绪存储在一个数组(all_emotions)中。在我的游戏中,情绪是随机选择的 - 并且图像被绘制到我的 Canvas 上。 emotype 是一个字符串。

currEmotion1 = randomEmotion(emotype);
// set image
emo1img = currEmotion1.emotionImg;

我的随机函数:

function randomEmotion(type) {
if(type == "happy") {
return all_emotions[0][Math.floor(Math.random()*all_emotions[0].length)];
}
else if(type == "sad") {
return all_emotions[1][Math.floor(Math.random()*all_emotions[0].length)];
}

有时,当调用我的随机函数时,我会收到错误:

类型错误:currEmotion1 未定义[Bei diesem Fehler anhalten]

emo1img = currEmotion1.emotionImg;

有人可以帮我吗?

最佳答案

randomEmotion函数中,当typesad时,您将根据all_emotions[0]<生成随机索引 但从 all_emotions[1] 读取,将其更改为下面的摘录,错误应该得到解决:

function randomEmotion(type) {
if(type == "happy") {
return all_emotions[0][Math.floor(Math.random()*all_emotions[0].length)];
}
else if(type == "sad") {
return all_emotions[1][Math.floor(Math.random()*all_emotions[1].length)];
}
}

关于JavaScript myObject 有时未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14354605/

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