如何从 JavaScript 数组中删除特定项?

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/9 23:40:17

假设我们有一个数字数组,我们向其中添加了元素。您需要设计一种简单的方法来从数组中删除特定元素。

以下是我们正在寻找的 −

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 ]

相关文章


有用资源