// 假设您有一个包含各种类型元素的数组
var elements = [
{ type: "button", content: "Button 1" },
{ type: "text", content: "Text 1" },
{ type: "button", content: "Button 2" },
{ type: "image", content: "Image 1" },
// ...
];
// 使用逆序循环来安全地删除指定类型的元素
for (var i = elements.length - 1; i >= 0; i--) {
if (elements[i].type === "button") {
elements.splice(i, 1);
}
}
// 数组现在不包含类型为 "button" 的元素
console.log(elements);
如果只能用splice方法,一定要用逆序循环