我的更新函数中有以下代码,每秒调用 30 次:
// Checking collision between rune and the players:
for(var j = 0; j < this.players.length; j++) {
if(this.checkCollision(this.players[j], this.runes[i])) {
this.runes[i].activate(this.players[j]);
this.runes[i].isHidden = true;
this.runes[i].onDeactivate = function() {
console.log(i);
self.runes.splice(i, 1);
}
}
}
在此之前我有:
for(var i = 0; i < this.runes.length; i++) ...
self.runes.splice(i, 1) 对数组没有任何作用... i 被设置为某个值。我只想从 rune 数组中删除不活动的 rune 。有什么想法吗?
最佳答案
你有两个问题。
首先,在调用 onDeactivate
时,i
将达到 this.runes.length
,这就是您将看到的内容在 console.log(i)
调用中。解决该问题的经典修复方法如下:
(function(i) {
// code that relies on i
})(i);
这实际上会“锁定”该闭包内容的 i
值。
第二个问题是 splice
修改了数组,而您无法接受。假设您有三个 rune :
[rune_0, rune_1, rune_2]
现在假设 rune_1
被停用,因此调用代码 splice(1,1)
将其删除。现在你的数组看起来像:
[rune_0, rune_2]
现在 rune_2
已停用,因此调用 splice(2,1)
。这会从数组中删除 [2]
元素...但已经没有了。
[rune_0, rune_2]
rune 仍然在那里。
要从数组中删除 rune ,您可以执行以下操作:
this.runes = this.runes.filter(function(rune) {return rune !== toremove;});
其中toremove
是您想要删除的 rune 。
关于javascript Array.splice() 不执行任何操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38280629/