【问题标题】:how to delete an entire element from an associative array in javascript如何从javascript中的关联数组中删除整个元素
【发布时间】: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) =&gt; ...)
  • @palaѕн 我试过了,它奏效了..谢谢你加载
  • 但是如何删除元素以使数组调整大小并且没有空白空间,也可以在 foreach 循环中删除元素?
  • 我不认为你可以。你需要像@Kooilnc所说的那样使用.filter,或者在循环外创建一个新数组,在循环内将符合条件的项目推入其中

标签: javascript arrays associative


【解决方案1】:

要从数组中删除符合特定条件的元素,Array.filter 会派上用场。见MDN

let arr1 = [1,2,3,4,5,6,7,8,9,10];
// [...] to stuff to arr1
arr1 = arr1.filter(val => val % 2 === 0);
console.log(arr1);

【讨论】:

    猜你喜欢
    • 2017-01-14
    • 1970-01-01
    • 2011-07-23
    • 2016-03-27
    • 1970-01-01
    • 2011-01-01
    • 2015-10-28
    • 1970-01-01
    • 2011-12-31
    相关资源
    最近更新 更多