如何从数组中删除对象,并在其内部添加函数

How to remove an object from an array, with a function within itself

本文关键字:内部 函数 添加 对象 数组 删除      更新时间:2023-09-26

我想通过使用内部函数来删除玩家[0]。这个例子是我的第一个想法,但它没有工作,请帮助我。

    // Stores the players
    var players = [];
    // Prototype of a new player
    var newPlayer = {
      hp: 100,
      xCord: 100,
      yCord: 100,
      // My try of removing player from inside itself
      removePlayer: function(){
          players.splice(0, 1);
      }
    }
    // Push the newPlayer prototype into the players array
    players.push(newPlayer);
    // Try to remove the player
    players[0].removePlayer();

在删除函数中尝试.indexOf(this)而不是0。这将在任意位置移除元素:

var players = [];
var newPlayer = {
  hp: 100,
  xCord: 100,
  yCord: 100,
  removePlayer: function() {
    players.splice(players.indexOf(this), 1);
  }
}
players.push("test");
players.push(newPlayer);
players.push("something");
console.log(players);
players[1].removePlayer();
console.log(players);

我不知道你说的

是什么意思

不工作

如果你把console.log(players);后你的代码,你会发现玩家数组是空的,所以你的代码工作。