【问题标题】:How to remove element before and after the index in an array如何删除数组中索引前后的元素
【发布时间】:2021-03-19 14:59:55
【问题描述】:

我有一个带有数组的数组:

[[], [0], []. [3], [], [6], []]

这些元素位于使用可拖动 JS 的 vue 组件中。 Draggable 有两个属性@start 和@end。每当我在数组中拖放元素时都会触发。每当我拖动其中一个元素时,我都想删除当前元素前后的空数组。所以当我拖动 [6] 时,数组应该是这样的:

[[], [0], []. [3], [6]]

isVisible 在@start 触发,所以每当我选择一个元素时。如何删除数组中索引前后的元素?我想用切片?

isVisible (val, index) {
   if (val[0] === 6) {
   this.array.splice(this.array[index - 1], 1)
   this.array.splice(this.array[index + 1], 1)
}

【问题讨论】:

  • 当修改一个可迭代对象,同时保持索引的一些状态时,需要小心。当您执行this.array.splice(this.array[index - 1], 1) 时,后面元素的索引会向上移动一个,因此您的索引不再有效。一个潜在的解决方案可能是改变调用的顺序,先删除后面的,然后再删除前面的。另外,我认为您误解了Array.prototype.splice 的签名。第一个参数是索引,而不是元素。
  • splice-remove 优选必须从数组的右侧到左侧进行处理,以免与想要splice-remove 的索引不同步。

标签: javascript arrays vue.js draggable vuedraggable


【解决方案1】:

删除之前的元素后,所有剩余元素的索引都会下移,因此之后的元素现在位于index,而不是index + 1

要避免这个问题,最简单的方法是先删除元素。

isVisible (val, index) {
    if (val[0] === 6) {
        this.array.splice(this.array[index + 1], 1)
        this.array.splice(this.array[index - 1], 1)
    }
}

请注意,如果这是循环的一部分,则需要向下调整循环索引以反映当前索引之前的元素已被删除。

【讨论】:

    【解决方案2】:

    另一种方法是过滤原始数组并返回一个包含所需数据的新数组:

    let arr = [ [], [0], [], [3], [], [6], [] ];
    console.log('Source:'+arr);
    
    function filterDragged(dragged, arr) {
      return arr.filter((e,i,a)=>{
        if ((a[i] && a[i].length==0) &&
            (a[i+1] && a[i+1].length!=0 && a[i+1][0]===dragged))
          return false;
    
        if ((a[i] && a[i].length==0) &&
            (a[i-1] && a[i-1].length!=0 && a[i-1][0]===dragged))
          return false;
    
        return true;
      });
    }
    
    console.log('Result:'+filterDragged(6, arr));
    console.log('Result:'+filterDragged(3, arr));

    【讨论】:

      猜你喜欢
      • 2023-01-13
      • 2011-07-10
      • 2016-05-20
      • 1970-01-01
      • 2014-03-18
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多