我只是混淆了为什么循环中的接头与多头接头的结果不同
示例:
var list = ["0","1","2","3","4"];
var removeIndex = [0,2,4];
情况1:
for (var i = removeIndex.length -1; i >= 0; i--)
list.splice(removeIndex[i],1);
结果:列表-> [1,3]
情况2:
list.splice(0,1);
list.splice(2,1);
list.splice(4,1);
结果:列表-> [1,2,4]
有人知道为什么吗?
#我明白了,那个向后循环的case1不像case2那样移动索引 我很愚蠢,我从某个地方复制了case1的代码,但我没有意识到(我总是认为循环是向前的)。
答案 0 :(得分:1)
您向后循环。无论如何,最好还是使用forEach。
const list = ["0","1","2","3","4"];
const removeIndex = [0,2,4];
removeIndex.forEach(item => list.splice(item,1))
console.log(list)
const list2 = ["0","1","2","3","4"];
list2.splice(0,1);
list2.splice(2,1);
list2.splice(4,1);
console.log(list2)