Quando js faz um loop no array, splice exclui o problema de atenção de dados

Quando js i ++ faz um loop na matriz, splice exclui os dados sem i--, e os dados obtidos estão errados:

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 corretamente:

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

 

 

 

Acho que você gosta

Origin blog.csdn.net/qq_40015157/article/details/113868742
Recomendado
Clasificación