เราจำเป็นต้องเขียนฟังก์ชันสำหรับอาร์เรย์ Array.prototype.remove() มันยอมรับ oneargument; เป็นฟังก์ชันเรียกกลับหรือองค์ประกอบที่เป็นไปได้ของอาร์เรย์ หากเป็นฟังก์ชัน ค่าตอบแทนของฟังก์ชันนั้นควรถือเป็นองค์ประกอบที่เป็นไปได้ของอาร์เรย์ และเราต้องค้นหาและลบองค์ประกอบนั้นออกจากอาร์เรย์ที่มีอยู่ และฟังก์ชันควรคืนค่าจริง หากพบองค์ประกอบและลบออก มิฉะนั้น ควรคืนค่าเป็นเท็จ .
ดังนั้น เรามาเขียนโค้ดสำหรับฟังก์ชันนี้กัน −
ตัวอย่าง
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' }
]