如何从数组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 ]