简体   繁体   English

从循环内的javascript数组中删除元素

[英]Removing an element from a javascript array inside a loop

I have the following code which iterates through a JS array. 我有以下代码,它遍历JS数组。 When I get to a specific element, I want to remove it. 当我到达特定元素时,我想删除它。 I realise that I can use splice, but is there a way that doesn't involve me tracking the index: 我意识到我可以使用拼接,但有一种方法不涉及我跟踪索引:

    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

        }
    });        

Modifying the array in-place can be tricky, so perhaps Array.filter() is a better function to use: 就地修改数组可能很棘手,因此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;
});     

It returns an array with all elements for which the callback returned true . 它返回一个数组,其中包含回调返回true所有元素。

There's often an issue with loops that change the length of the array being looped over. 循环通常会出现问题,这会改变循环播放的数组的长度。 They will end up 'skipping' an item. 他们最终会“跳过”一件物品。

It's typical when you're going to affect the length of the array to count down instead of up, with a loop like this: 通常情况下,当您要影响数组的长度而不是向上计数时,使用如下循环:

for (var i = Things.length - 1; i >= 0; i--) {
  //your code here
};

Use the 2nd parameter to forEach , index and Array.splice : 使用第二个参数来表示forEachindexArray.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM