使用splice()从数组中删除与条件匹配的项目 [英] Using splice() to remove items that matches condition from array

查看:355
本文介绍了使用splice()从数组中删除与条件匹配的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im trying to via a for-loop remove all the items that matches a condition in the state array. But it seems to only be removing the last items in the array and not the ones that matches. Am I using the .splice() incorrectly? Thanks in advance. Code is:

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)
       }

推荐答案

这是一个经典问题;您将同时迭代并缩小数组,因此最终将跳过记录.

This is a bit of a classic problem; you're iterating forward and shrinking the array at the same time so you're going to end up skipping over records.

我建议使用 Array.prototype.filter() 代替

I suggest using Array.prototype.filter() instead

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

这会将数组缩小为sg_categories属性不包含"travel" 的条目.

This will reduce the array to entries who's sg_categories property does not include "travel".

这篇关于使用splice()从数组中删除与条件匹配的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆