如何从javascript中的关联数组中删除整个元素

问题描述 投票:0回答:1

我在javascript中不太好。我有一个关联数组,在其中放置了一些值。现在要遍历该数组,我正在使用一个foreach循环。在foreach循环中,如果满足条件,我要删除整个元素,并且不希望在数组中留有空白空间以提高效率。但是,我不知道如何从foreach循环中获取数组的索引。

here is my code:
for(var j = 0 ; j < i; j++){
        obstacles.push({ width:35, height:35, x:initialX, y:initialY});
    }

 //to iterate through the array
  obstacles.forEach(o => {
          o.x -= 2;
          context.fillRect(o.x, o.y, o.width, o.height); //create a rectangle with the elements inside the associative array
          //I need to get the index and delete the entire element and afterwards the array should resize with the other elements' index updated

        }
javascript arrays associative
1个回答
0
投票

要从数组中删除符合特定条件的元素,请使用Array.filter。参见MDN

© www.soinside.com 2019 - 2024. All rights reserved.