我们需要为数组Array.prototype.remove()写一个函数。它接受一个论点。它可以是回调函数,也可以是数组的可能元素。如果它是一个函数,则应将该函数的返回值视为数组的可能元素,我们必须从数组中查找并删除该元素,如果找到并删除了该元素,则函数应返回true应该返回false。
因此,让我们为该函数编写代码-
示例
const arr = [12, 45, 78, 54, 1, 89, 67];
const names = [{
fName: Aashish,
lName: Mehta
}, {
fName: Vivek,
lName: Chaurasia
}, {
fName: Rahul,
lName: Dev
}];
const remove = function(val){
let index;
if(typeof val === function){
index = this.findIndex(val);
}else{
index = this.indexOf(val);
};
if(index === -1){
return false;
};
return !!this.splice(index, 1)[0];
};
Array.prototype.remove = remove;
console.log(arr.remove(54));
console.log(arr);
console.log(names.remove((el) => el.fName === Vivek));
console.log(names);
输出结果
控制台中的输出将为-
true
[ 12, 45, 78, 1, 89, 67 ]
true
[
{ fName: Aashish, lName: Mehta },
{ fName: Rahul, lName: Dev }
]