When js loops the array, splice deletes the data attention problem

When js i++ loops the array, splice deletes the data without i--, and the data obtained is wrong:

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

 use correctly:

// 去掉 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);

 

 

 

Guess you like

Origin blog.csdn.net/qq_40015157/article/details/113868742