首页 > 解决方案 > 我的方法和函数在数组数组中不起作用

问题描述

我有一个二维数组,它是一个游戏板。我创建了一些对象玩家、武器等,它们也保存在自己的阵列中。到目前为止,这很好。我可以创建对象更新它们的属性等。

我现在正在尝试为游戏创建一些方法和功能。例如; 玩家拿起武器并更新属性以显示这一点。

我已经在一个数组中尝试了这些方法并且它工作了,只要我把它做成一个或多个数组,我就遇到了麻烦。

class Player {
  constructor(name, players, hp) {
    this.name = name;
    this.players = players;
    this.hp = 100;
    this.currentWeapon = null;
  }
  pickUp(weapons) {
    this.currentWeapon = weapons;
    weapons.hold = true;
    weapons.player = this;
  }
  dropOff(weapon) {
    this.currentWeapon = null;
    weapon.hold = false;
    weapon.player = null;
  }


  class Weapon {
    constructor(name, id, damage, weapons) {
      this.name = name;
      this.id = id;
      this.damage = damage;
      this.weapons = weapons;
      this.player = null;
      this.hold = false;
    }
  }


  players.pickUp(weapons);
  players.dropOff(weapons);

我基本上希望在调用函数时更新 currentWeapon 以及 this.player 和 this.hold 属性。

我也将每个类都存储为它们自己的数组。

当我运行它时,它要么说 XXX 不是函数,要么没有定义 XXX。

玩家和武器都在一个阵列的阵列上,即棋盘。

任何想法,将不胜感激!

谢谢!

标签: javascriptfunctionoopmultidimensional-arraymethods

解决方案


我有根据的猜测是在你的代码中的某个地方你有类似的东西:

const players = []
players.push(new Player(...))  // in a for loop

如果是这种情况,并且您希望一系列玩家有一个方法pickUp,那就是您的问题。
每个玩家对象都有一个拾取方法而不是玩家(玩家数组)。

可能的解决方案:

players.forEach(player => player.pickUp(weapons));
players.forEach(player => player.dropOff(weapons));

推荐阅读