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


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

更新于:2020 年 8 月 25 日

210 次浏览

开启您的 职业

完成课程即可获得认证

开始
广告
© . All rights reserved.