标签:com font alt splice code ice length asc 索引
var data = [ { isRemove: 0, name: "叶明龙1" }, { isRemove: 1, name: "叶明龙2" }, { isRemove: 1, name: "叶明龙3" }, { isRemove: 0, name: "叶明龙4" }, { isRemove: 0, name: "叶明龙5" }, { isRemove: 0, name: "叶明龙6" }, { isRemove: 1, name: "叶明龙7" }, { isRemove: 1, name: "叶明龙8" } ];
正常的思路是for循环然后if判断,在用数组的splice方法来移除。但是,这种思路会造成索引错乱。那么我们推荐下面的解决方案:
for (var i = data.length - 1; i >= 0; i--) { if (data[i].isRemove) { data.splice(i, 1); } }
再推荐一个高效的写法:
var i = data.length; while (i--) { if (data[i].isRemove) { data.splice(i, 1); } }
如果这篇文章对您有帮助,您可以打赏我
技术交流QQ群:15129679
标签:com font alt splice code ice length asc 索引
原文地址:https://www.cnblogs.com/yeminglong/p/9833872.html