JavaScript for循环splice()方法删除数组中的元素会被跳过或者只能删除部分

for of 中使用

arr.splice(arr.indexOf(element), 1, null);

把这个索引下的东西删除数量1,然后替换成null

 

下面是个倒序循环,会回避splice的错误

 

let arr = [
		{id:1,name:'Tom',sex:0},
		{id:2,name:'Jerry',sex:1},
		{id:3,name:'Danny',sex:1},
		{id:4,name:'Jenny',sex:0},
		{id:6,name:'Lee',sex:0},
		{id:5,name:'Bob',sex:1},
		{id:7,name:'John',sex:0},
		{id:8,name:'Marry',sex:1}
	];
	
	for(let i=arr.length-1;i>=0;i--){
		if(arr[i].sex === 1){
			arr.splice(i,1);
		}
	}

 

参考:https://blog.csdn.net/weixin_42048134/article/details/85232677

你可能感兴趣的:(错误解决,javascript)