【发布时间】: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以处理移动到已删除项目位置的项目。