JavaScript myObject有时未定义

JavaScript myObject有时未定义,javascript,object,undefined,Javascript,Object,Undefined,嗨,我在JavaScript方面遇到了一些问题。 虽然我浏览了以前的一些帖子,但还没有找到答案 我正在开发一个HTML5+Javascript游戏,其中我有一个情感对象: emotionImg是一个图像,type是一个字符串 function Emotion(emotionImg, type) { this.emotionImg = emotionImg; this.emotionImg.onload = function() { console.log("added emotion:

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

我正在开发一个HTML5+Javascript游戏,其中我有一个情感对象: emotionImg是一个图像,type是一个字符串

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;
}

这些情绪存储在所有情绪的数组中。在我的游戏中,情绪是随机选择的——图像被绘制到我的画布上。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)];
}
有时,调用随机函数时,会出现以下错误:

TypeError:Currenomation1未定义 [Bei diesem Fehler anhalten]

emo1img=currenemotion1.emotionImg

有人能帮我吗?

在randomEmotion函数中,当类型为sad时,您将基于所有情绪[0]生成一个随机索引,但读取所有情绪[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)];
  }
}

如果所有情绪[0]中的项目比所有情绪[1]中的项目多,那么如果类型为sad,则可能会出现错误-您从0中选择了一个随机索引,从1中读取。谢谢!这是一个看不见的愚蠢错误。。我希望这就是问题所在@steveukx接球不错!应该是问题所在,值得回答。