如何从数组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 20岁简短生日祝福语
14 夸赞老师祝福语搞笑简短
15 浪漫的生日祝福语简短
16 文艺结婚祝福语短语简短
17 邻家生小孩祝福语简短
18 护士辞职送行祝福语简短