如何从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' }
]热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短