如何从数组中删除对象,并在其内部添加函数
How to remove an object from an array, with a function within itself
我想通过使用内部函数来删除玩家[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);
后你的代码,你会发现玩家数组是空的,所以你的代码工作。
相关文章:
- 我可以从内部函数中产生吗?
- 从内部函数javascript内部分配外部函数的对象
- 将外部函数返回的id传递给内部函数
- 重复调用的同一函数会重置setTimeout内部函数
- Javascript中的内部函数作用域
- 对象内部函数内的对象文本的范围
- 内部函数不会为外部函数在 jQuery 中动态创建的元素赋值
- JavaScript 如何定义内部函数
- bluebird promise catch() 没有使用 Promise.CancelError 调用内部函数
- JavaScript 在内部函数中保留一个 var
- 如何使用Javascript访问内部函数
- 使用从内部函数返回的异步数据对外部函数返回promise
- Javascript对象看不到内部函数
- 为什么可以在内部函数成员中访问对象引用,而不能在内部属性成员中访问
- 如何将参数传递到内部函数中
- JavaScriptEs6在内部函数中引用了这一点
- 需要将内部函数绑定到元素的单击事件
- 将此对象传递给JavaScript中的内部函数
- JavaScript 面向对象的调用函数内部函数或调用函数 insede var
- 从内部函数内部突破while循环'的身体