如何从数组JavaScript中删除特定项目?
假设我们有一个数字数组,并向其中添加了元素。您需要设计一种简单的方法来从数组中删除特定元素。
以下是我们正在寻找的-
array.remove(number);
我们必须使用核心JavaScript。不允许使用框架。
示例
为此的代码将是-
const arr = [2, 5, 9, 1, 5, 8, 5];
const removeInstances = function(el){
const { length } = this;
for(let i = 0; i < this.length; ){
if(el !== this[i]){
i++;
continue;
}
else{
this.splice(i, 1);
};
};
//如果删除了任何项目,则返回true,否则返回false-
if(this.length !== length){
return true;
};
return false;
};
Array.prototype.removeInstances = removeInstances;
console.log(arr.removeInstances(5));
console.log(arr);输出结果
控制台中的输出将是-
true [ 2, 9, 1, 8 ]
热门推荐
10 收到乔迁礼物祝福语简短
11 春节给大家祝福语简短
12 温馨顺德婚礼祝福语简短
13 结婚祝福语嫂子的话简短
14 团队入伙简短祝福语大全
15 客户激活花束祝福语简短
16 感恩卡片的祝福语 简短
17 表姐孩子满月祝福语简短
18 美术分班祝福语简短精辟