如何在 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 ]

更新於: 24-11-2020

230 瀏覽

開啟你的 事業

完成課程,獲得認證

立即開始
廣告