如何在 JavaScript 中从数组中删除特定项

javascriptweb developmentobject oriented programming更新于 2025/10/8 17:16:17

我们需要为数组编写一个函数 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' }
]

相关文章


有用资源