如何在 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);
};
};
// if any item is removed return true, false otherwise
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 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP