未捕获的TypeError:无法设置未定义的属性"0" [英] Uncaught TypeError: Cannot set property '0' of undefined

查看:97
本文介绍了未捕获的TypeError:无法设置未定义的属性"0"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将值插入数组,但是当我尝试插入值时,它为我提供了未定义的Connot设置属性"0".但显然我已经定义了数组.

I am trying to insert a value into an array but when i try to insert the value it gives me the Connot set Property '0' of undefined. But clearly i defined the array already.

错误行:

this.enemyMinions[i] = new EnemyCombatMinion(new Minion(enemyMinionInfo[0], 0, enemyMinionInfo[1], enemyMinionInfo[2], enemyMinionInfo[3], 0, 0, 0, 0, 0, 0));

这是完整的代码:

function Combat() {
  this.enemyMinions = [];
  this.playerMinions = [];
  this.currentEnemyMinion = null;
  this.currentPlayerMinion = null;
}

Combat.prototype.initialize = function() {
  var o = 0;
  for(var i = 0; i < partySlots.length; i++) {
    if(partySlots[i]) {
      this.playerMinions[o] = PlayerCombatMinion(partySlots[i]);
      o++;
    }
  }
  this.currentPlayerMinion = this.playerMinions[0];

   $.ajax({
      url: "./api/generateEnemyCombatMinions.php",
      cache: false
    })
    .done(function( html ) {          
      var response = html.split(":::");
      for(var i = 0; i < response.length; i++) {
        var enemyMinionInfo = response[i].split("::");
        this.enemyMinions[i] = new EnemyCombatMinion(new Minion(enemyMinionInfo[0], 0, enemyMinionInfo[1], enemyMinionInfo[2], enemyMinionInfo[3], 0, 0, 0, 0, 0, 0));
      }
      alert(this.enemyMinions.length);
    });   

}

如您所见,我在类构造函数中将this.enemyMinons声明为文字,并尝试在initialize方法中为其定义一个值.

As you see, i declared this.enemyMinons as a literal in the class constructor, and try to define a value to it in the initialize method.

推荐答案

done()回调不将您的 Combat 对象用作 this .在 initialize()函数中保存指向该对象的指针,以便以后可以访问该对象.

The done() callback does not use your Combat object as this. Save a pointer to the object in the initialize() function, so that you can access the object later on.

Combat.prototype.initialize = function() {
  var o = 0;
  for(var i = 0; i < partySlots.length; i++) {
    if(partySlots[i]) {
      this.playerMinions[o] = PlayerCombatMinion(partySlots[i]);
      o++;
    }
  }
  this.currentPlayerMinion = this.playerMinions[0];

  // this is new
  var that= this;

   $.ajax({
      url: "./api/generateEnemyCombatMinions.php",
      cache: false
    })
    .done(function( html ) {          
      var response = html.split(":::");
      for(var i = 0; i < response.length; i++) {
        var enemyMinionInfo = response[i].split("::");
        // use "that" here instead of "this"
        that.enemyMinions[i] = new EnemyCombatMinion(new Minion(enemyMinionInfo[0], 0, enemyMinionInfo[1], enemyMinionInfo[2], enemyMinionInfo[3], 0, 0, 0, 0, 0, 0));
      }
      alert(that.enemyMinions.length);
    });   

}

这篇关于未捕获的TypeError:无法设置未定义的属性"0"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆