我想从我的精灵数组中删除一个精灵,我尝试了myPlane.bullets[index].destroy()
和myPlane.bullets.shift()
:
for (let index = 0; index < myPlane.bullets.length; index++) {
if(myPlane.bullets[index].y < -bulletHeight) {
// step 1
myPlane.bullets[index].destroy()
// step 2
myPlane.bullets.shift()
continue
}
myPlane.bullets[index].y -= bulletSpeed
}
但我认为这不是删除数组中的精灵的最佳方式,它太繁琐了。
是否有更好的方法来删除一个数组中的精灵?
不幸的是,myPlane.bullets.shift()
只会删除数组的第一个元素。要通过索引删除元素,您需要使用myPlane.bullets.splice(i, 1)
。
请记住,这会影响对象的原始索引。如果不处理,for循环将继续递增,并跳过一个元素。
for (let index = 0; index < myPlane.bullets.length; index++) {
if (myPlane.bullets[index].y < -bulletHeight) {
// step 1
myPlane.bullets[index].destroy()
// step 2
myPlane.bullets.splice(index, 1)
index-- // compensate array length mutation
continue
}
myPlane.bullets[index].y -= bulletSpeed
}
一般来说,应该避免改变循环遍历的数组。如果您不保留对bullets
数组的引用,这里有一个替代方法,其中创建了一个新的过滤数组:
myPlane.bullets = myPlane.bullets.filter((bullet) => {
if (bullet.y < -bulletHeight) {
bullet.destroy()
return false
}
return true
});
for (let index = 0; index < myPlane.bullets.length; index++) {
myPlane.bullets[index].y -= bulletSpeed
}