Cuando js hace un bucle en la matriz, el empalme elimina el problema de atención de datos

Cuando js i ++ repite la matriz, splice elimina los datos sin i--, y los datos obtenidos son incorrectos:

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

 utilizar correctamente:

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

 

 

 

Supongo que te gusta

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