【JS数组】在数组原型上实现删除某一个元素的方法
Array.prototype.remove = function (item) {
const index = this.indexOf(item);
if (index > -1) {
this.splice(index, 1);
}
};
test() {
const arr1 = [
{ id: 1, age: 12 },
{ id: 2, age: 13 },
{ id: 3, age: 14 }
];
// 注意:indexOf只能查找相同地址的对象, 引用地址不同的话,查找不到
// 所以:如果删除的元素是对象类型, 所删除元素必须和数组内部元素对象指向同一地址
const item = arr1[1];
arr1.remove(item);
console.log("arr1---------test-----", arr1);
const arr2 = ["a","b","c","d"]
arr2.remove("b")
console.log('arr2----------', arr2)
}
test()
文章介绍了如何在JavaScript数组的原型上自定义一个remove方法,以便删除指定元素,特别指出当删除的对象是引用类型时,需确保其引用地址与数组内元素一致。示例展示了使用该方法删除数组中的对象和基本数据类型。
228

被折叠的 条评论
为什么被折叠?



