[英]Removing an element from a javascript array inside a loop
我有以下代碼,它遍歷JS數組。 當我到達特定元素時,我想刪除它。 我意識到我可以使用拼接,但有一種方法不涉及我跟蹤索引:
myArray.forEach(function (point) {
canvasContext.clearRect(point.PointX - 3, point.PointY - 3, 6, 6);
point.PointY++;
canvasContext.fillRect(point.PointX - 3, point.PointY - 3, 6, 6);
if (point.PointY > canvas.height) {
// Remove point
}
});
就地修改數組可能很棘手,因此Array.filter()
可能是一個更好的函數:
myArray = myArray.filter(function (point) {
canvasContext.clearRect(point.PointX - 3, point.PointY - 3, 6, 6);
point.PointY++;
canvasContext.fillRect(point.PointX - 3, point.PointY - 3, 6, 6);
if (point.PointY > canvas.height) {
return false;
}
return true;
});
它返回一個數組,其中包含回調返回true
所有元素。
循環通常會出現問題,這會改變循環播放的數組的長度。 他們最終會“跳過”一件物品。
通常情況下,當您要影響數組的長度而不是向上計數時,使用如下循環:
for (var i = Things.length - 1; i >= 0; i--) {
//your code here
};
使用第二個參數來表示forEach
, index
和Array.splice
:
myArray.forEach(function (point, index) {
canvasContext.clearRect(point.PointX - 3, point.PointY - 3, 6, 6);
point.PointY++;
canvasContext.fillRect(point.PointX - 3, point.PointY - 3, 6, 6);
if (point.PointY > canvas.height) {
myArray.splice(index, 1);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.