我通过参数获取数组并获取索引 然后我拼接,但是我的this.players还是一样。
makeMatch(condition) {
const matchedPlayers = this.players.filter(condition);
this.removePlayers(matchedPlayers);
return new Match(matchedPlayers);
}
removePlayers(players) {
players.forEach(p => {
this.removePlayer(p);
});
}
removePlayer(player) {
const index = this.players.findIndex(p => p.id === player.id);
console.log(index);
if (index > -1) {
this.players.splice(index, -1);
}
console.log(this.players);
}
在我的索引上使用 splice 后,我的播放器集合保持不变
即使在使用后也要从列表中删除。切片我的列表保持相同的大小
我的函数将玩家添加到我的数组中
// addPlayers add multiple players into queue
addPlayers(players) {
this.players = this.players.concat(players);
}
// addPlayer adds a single player into queue
addPlayer(player) {
this.players.push(player);
}
最佳答案
您将 -1
作为第二个参数传递给 splice
,它应该是要删除的项目数(即 1
)。
此外,还可以简化 removePlayer
并且根本不使用 splice
:
removePlayer(player) {
this.players = this.players.filter(p => p.id !== player.id)
}
关于javascript - 删除和添加到数组的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59024037/