【发布时间】:2020-04-05 16:25:35
【问题描述】:
我在 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
}
【问题讨论】:
-
你的意思是这个数组索引:
obstacles.forEach((o, index) => ...) -
@palaѕн 我试过了,它奏效了..谢谢你加载
-
但是如何删除元素以使数组调整大小并且没有空白空间,也可以在 foreach 循环中删除元素?
-
我不认为你可以。你需要像@Kooilnc所说的那样使用.filter,或者在循环外创建一个新数组,在循环内将符合条件的项目推入其中
标签: javascript arrays associative