【问题标题】:Using splice() to remove items that matches condition from array使用 splice() 从数组中删除匹配条件的项目
【发布时间】:2019-09-06 04:18:06
【问题描述】:

我试图通过 for 循环删除与状态数组中的条件匹配的所有项目。但它似乎只删除了数组中的最后一项,而不是匹配的项。我是否错误地使用了 .splice() ?提前致谢。代码是:

rmTravel() {
           for(var i = 0; i < this.cards.length; i++){
               if(this.cards[i].sg_categories.includes("travel")){
                   this.cards.splice(i, 1);
                   console.log('Removed following card:', this.cards[i].slug)
               }
           }
           console.log('Cards in cards state: ', this.cards)
       }

【问题讨论】:

  • 1. 如果splice() 应该从数组中删除一个项目,那么您的console.log() 调用是不是太晚了?您不应该在删除项目之前打印它吗? 2. 当您从数组中删除一个项目时,以下项目不会向数组的开头移动一个位置吗?如果是这样,您可能应该在删除后减少 i 以处理移动到已删除项目位置的项目。

标签: json vue.js


【解决方案1】:

这是一个有点经典的问题;您正在向前迭代并同时缩小数组,因此您最终会跳过记录。

我建议改用Array.prototype.filter()

this.cards = this.cards.filter(({ sg_categories }) => 
    !sg_categories.includes('travel'))

这会将数组减少为sg_categories 属性不包含“travel”的条目。

【讨论】:

  • 太棒了。这就是我一直在寻找的。谢谢。
猜你喜欢
  • 1970-01-01
  • 2018-06-25
  • 2012-12-04
  • 1970-01-01
  • 2019-09-22
  • 1970-01-01
  • 1970-01-01
  • 2014-06-28
  • 1970-01-01
相关资源
最近更新 更多