如何从数组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 ]
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便