Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

배열 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 ]