简体   繁体   English

使用拼接从数组中删除项目

[英]Remove item from array using splice

I am using Vue JS, I have 2 different arrays categories and items . 我正在使用Vue JS,我有2个不同的数组categoriesitems Each item can belong to multiple categories, the items are generated dynamically and therefore not initially associated in the category array. 每个项目都可以属于多个类别,这些项目是动态生成的,因此最初不在类别数组中关联。 Then I parse the category array to create tables containing the different items. 然后,我分析类别数组以创建包含不同项目的表。

For testing purposes, I attach the items to it's associated category in the mounted vue property, as follows: 出于测试目的,我将这些项附加到已挂载的vue属性中与其关联的类别,如下所示:

mounted: function() {
  for (let item of this.items) {
    for (let category of item.categories) {
      this.categories[category - 1].items.push(item)
    }
  }
}

Then when the delete button is pressed, I trigger a deleteItem method which uses splice to delete the item from the categories array and from the items array as well, but I am having a little issue there that the correct item does not get deleted. 然后按下删除按钮时,我触发deleteItem它使用拼接,以删除的项目方法categories排列,并从items阵列为好,但我有一个小问题上有正确的项目不会被删除。

  methods: {
    deleteItem: function(item) {
      for (let category of item.categories) {
        this.categories[category - 1].items.splice(this.categories[category - 1].items.indexOf(item, 1))
      }
      this.items.splice(this.items.indexOf(item, 1))
    }
  }

Please see the example Fiddle . 请参阅示例Fiddle Any help will be appreciated. 任何帮助将不胜感激。

Change 更改

this.items.splice(this.items.indexOf(item, 1))

to

this.items.splice(this.items.indexOf(item), 1)

so that you pass 1 as second argument to splice . 这样就可以将1作为第二个参数传递给splice

Note that you do the same error twice. 请注意,您两次执行相同的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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