js 循环数组时,splice 删除数据注意的问题

js i++循环数组时,splice 删除数据没有i-- ,得到的数据错误:

let rId = 2;
let list = [{id: 1, name: "a"}, {id: 4, name: "d"}, {id: 3, name: "c"}, {id: 2, name: "b"}];

// 去掉 id 大于 2 的数据
for (let i = 0; i < list.length; i++) {
    if (list[i].id > rId) {
        list.splice(i, 1);
    }
}
console.log(list);

 正确使用:

// 去掉 id 大于 2 的数据
for (let i = 0; i < list.length; i++) {
    if (list[i].id > rId) {
        list.splice(i, 1);
        i--; //因为数组本身变了,长度变了,数组元素向前移了一步,所以循环也要往前移一步
    }
}
console.log(list);
// 或者直接循环时i--
for (let i = list.length - 1; i >= 0; i--) {
    if (list[i].id > rId) {
        list.splice(i, 1);
    }
}
console.log(list);

猜你喜欢

转载自blog.csdn.net/qq_40015157/article/details/113868742
今日推荐