3

我有以下代码遍历 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

        }
    });        
4

3 回答 3

1

Modifying the array in-place can be tricky, so perhaps Array.filter() is a better function to use:

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;
});     

It returns an array with all elements for which the callback returned true.

于 2013-04-19T16:51:36.227 回答
0

使用第二个参数forEach,indexArray.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);
    }
});
于 2013-04-19T16:41:58.517 回答
0

循环经常会出现一个问题,它会改变被循环的数组的长度。他们最终会“跳过”一个项目。

当您要影响数组的长度以倒计时而不是向上倒计时时,这是典型的,使用如下循环:

for (var i = Things.length - 1; i >= 0; i--) {
  //your code here
};
于 2013-04-19T16:50:08.100 回答