方法体内部使用splice方法,在使用for循环或者forEach遍历数组的话,删除数据不全
方法一 ,用逆向循环
for (let index = _this.teamIds.length - 1; index >= 0 ; index--) {
if(_this.teamIds[index].indexOf(val) == '-1'){
_this.teamIds.splice(index, 1);
}
}
方法二,用filter
var arr = [1, 2, 3, 4, 5];
arr = arr.filter(item => item == 4);
console.log(arr); //数组只留下4
本文介绍了在JavaScript中使用splice方法删除数组元素时可能遇到的问题,并提供了两种解决方案:逆向循环和filter方法。逆向循环可以避免因索引变化导致的数据删除不全问题,而filter方法则提供了一种更简洁的实现方式。

被折叠的 条评论
为什么被折叠?



