programing

JavaScript에서 배열 요소 삭제 - 삭제 vs 스플라이스

firstcheck 2023. 1. 31. 20:59
반응형

JavaScript에서 배열 요소 삭제 - 삭제 vs 스플라이스

어레이 요소에서 연산자를 사용하는 것과 메서드를 사용하는 것의 차이점은 무엇입니까?

예를 들어 다음과 같습니다.

myArray = ['a', 'b', 'c', 'd'];

delete myArray[1];
//  or
myArray.splice (1, 1);

객체에서와 같이 어레이 요소를 삭제할 수 있는데 왜 스플라이스 방식을 사용할 수 있습니까?

delete는 오브젝트 속성을 삭제하지만 어레이의 인덱스를 다시 작성하거나 길이를 갱신하지 않습니다.이것에 의해, 정의되어 있지 않은 것처럼 표시됩니다.

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> delete myArray[0]
  true
> myArray[0]
  undefined

값은 되어 있지 .undefined어레이에서 속성이 삭제되어 정의되지 않은 것으로 표시됩니다.Chrome 개발 도구는 인쇄를 통해 이러한 차이를 명확히 합니다.empty어레이를 로깅할 때.

> myArray[0]
  undefined
> myArray
  [empty, "b", "c", "d"]

myArray.splice(start, deleteCount) 는 실제로 요소를 삭제하고 어레이를 재인덱스하여 길이를 변경합니다.

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> myArray.splice(0, 2)
  ["a", "b"]
> myArray
  ["c", "d"]

Array.remove() 메서드

jQuery의 창시자인 John Resig는 매우 편리한 도구를 만들었다.Array.remove이치노

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

사용 방법의 예를 다음에 나타냅니다.

// Remove the second item from the array
array.remove(1);
// Remove the second-to-last item from the array
array.remove(-2);
// Remove the second and third items from the array
array.remove(1,2);
// Remove the last and second-to-last items from the array
array.remove(-2,-1);

존의 웹사이트

delete는 어레이의 요소에서 개체만 제거하기 때문에 어레이의 길이는 변경되지 않습니다.스플라이스는 객체를 제거하고 어레이를 단축합니다.

다음 코드는 "a", "b", "정의되지 않음", "d"로 표시됩니다.

myArray = ['a', 'b', 'c', 'd']; delete myArray[2];

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}

단, "a", "b", "d"로 표시됩니다.

myArray = ['a', 'b', 'c', 'd']; myArray.splice(2,1);

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}

어레이에서 발생하는 요소를 모두 삭제하는 방법을 이해하려고 하다가 우연히 이 질문을 발견했습니다.의 비교는 다음과 같습니다.splice ★★★★★★★★★★★★★★★★★」delete 것을 위해서'c' items

var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];

while (items.indexOf('c') !== -1) {
  items.splice(items.indexOf('c'), 1);
}

console.log(items); // ["a", "b", "d", "a", "b", "d"]

items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];

while (items.indexOf('c') !== -1) {
  delete items[items.indexOf('c')];
}

console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
​

[ Core JavaScript 1.5 Reference ]> [ Operators ]> [ Special Operators ]> [ delete Operator ]에서 다음 순서를 수행합니다.

어레이 요소를 삭제해도 어레이 길이는 영향을 받지 않습니다.예를 들어 a[3]를 삭제해도 a[4]는 a[4]이고 a[3]는 정의되지 않습니다.이는 배열의 마지막 요소를 삭제한 경우에도 유지됩니다([a.length-1] 삭제).

번 한 바와 같이, 「」를 합니다.splice()딱 맞는 것 같아요.Mozilla에 있는 문서:

이 메서드는 기존 요소를 제거하거나 새 요소를 추가하여 배열 내용을 변경합니다.

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];

myFish.splice(2, 0, 'drum'); 
// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]

myFish.splice(2, 1); 
// myFish is ["angel", "clown", "mandarin", "sturgeon"]

구문

array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1, item2, ...)

파라미터

개시하다

어레이 변경을 시작할 인덱스입니다.어레이 길이보다 클 경우 실제 시작 인덱스는 어레이 길이로 설정됩니다.음의 경우는, 그 많은 요소가 끝으로부터 개시됩니다.

delete Count(삭제 카운트)

제거할 이전 배열 요소의 수를 나타내는 정수입니다.deleteCount가 0인 경우 요소는 삭제되지 않습니다.이 경우 하나 이상의 새 요소를 지정해야 합니다.deleteCount가 시작 시 어레이에 남아 있는 요소의 수보다 클 경우 어레이의 끝에 있는 모든 요소가 삭제됩니다.

는 delete Count와 .(arr.length - start).

항목 1, 항목 2, ...

배열에 추가할 요소. 이치노 " " " 입니다.splice()는 배열에서 요소만 삭제합니다.

반환값

삭제된 요소를 포함하는 배열입니다.1개의 요소만 삭제되면 1개의 요소의 배열이 반환됩니다.요소가 제거되지 않으면 빈 배열이 반환됩니다.

[...]

splice는 숫자 인덱스와 함께 작동합니다.

, 「」입니다.delete다른 종류의 지수에 대해 사용할 수 있습니다.

예:

delete myArray['text1'];

또한 스플라이스는 어레이에서만 작동한다는 점도 언급할 가치가 있습니다(오브젝트 속성은 일관된 순서를 따를 수 없습니다).

객체에서 키와 값의 쌍을 삭제하려면 실제로 delete를 선택합니다.

delete myObj.propName;     // , or:
delete myObj["propName"];  // Equivalent.

삭제와 스플라이스

배열에서 항목을 삭제할 때

var arr = [1,2,3,4]; delete arr[2]; //result [1, 2, 3:, 4]
console.log(arr)

스플라이스 할 때

var arr = [1,2,3,4]; arr.splice(1,1); //result [1, 3, 4]
console.log(arr);

요소가 삭제되었지만 인덱스는 비어 있는 경우

반면 스플라이스 요소가 삭제되고 그에 따라 휴지 요소의 지수가 감소하는 경우

delete는 실제와는 다른 상황처럼 동작하며 항목을 제거할 어레이 길이는 그대로 유지됩니다.

노드 단말기의 예:

> var arr = ["a","b","c","d"];
> delete arr[2]
true
> arr
[ 'a', 'b', , 'd', 'e' ]

다음으로 slice()사용하여 배열 항목을 인덱스로 삭제하는 함수를 나타냅니다.arr은 첫 번째 arg로, 삭제할 멤버의 인덱스는 두 번째 인수로 사용합니다.보시다시피 어레이의 멤버를 실제로 삭제하고 어레이 길이를 1개 줄입니다.

function(arr,arrIndex){
    return arr.slice(0,arrIndex).concat(arr.slice(arrIndex + 1));
}

위의 함수는 모든 멤버와 인덱스 뒤의 모든 멤버를 인덱스로 이동시켜 이들을 연결하고 결과를 반환합니다.

위의 함수를 노드모듈로 사용하는 예를 다음에 나타냅니다.단말기를 참조하면 편리합니다.

> var arr = ["a","b","c","d"]
> arr
[ 'a', 'b', 'c', 'd' ]
> arr.length
4 
> var arrayRemoveIndex = require("./lib/array_remove_index");
> var newArray = arrayRemoveIndex(arr,arr.indexOf('c'))
> newArray
[ 'a', 'b', 'd' ] // c ya later
> newArray.length
3

indexOf("c")는 첫 번째 오카렌스만 취득하고 발견된 첫 번째 오카렌스만 분리하여 삭제하기 때문에 이 방법은 dupes가 포함된 어레이에서는 작동하지 않습니다.

대규모 배열을 반복하여 요소를 선택적으로 삭제하려면 삭제 때마다 splice()를 호출해야 합니다.이는 splice()가 매번 후속 요소를 다시 인덱싱해야 하기 때문입니다.어레이는 Javascript와 관련되어 있으므로 개별 요소를 삭제하고 나중에 어레이를 다시 인덱싱하는 것이 더 효율적입니다.

새로운 어레이를 구축하면 됩니다.

function reindexArray( array )
{
       var result = [];
        for( var key in array )
                result.push( array[key] );
        return result;
};

그러나 원래 어레이의 키 값은 변경할 수 없다고 생각합니다.그것이 더 효율적입니다.새로운 어레이를 작성해야 할 것 같습니다.

"정의되지 않은" 엔트리는 실제로 존재하지 않으며 for loop에서는 반환되지 않으므로 확인할 필요가 없습니다.정의되지 않은 것으로 표시되는 어레이 인쇄의 아티팩트입니다.그것들은 기억 속에 존재하지 않는 것 같다.

더 빠른 슬라이스()를 사용할 수 있으면 좋겠지만 재인덱스는 되지 않습니다.더 좋은 방법 아는 사람?


실제로 다음과 같이 효율적으로 퍼포먼스 면에서 실행할 수 있습니다.

reindexArray : function( array )
{
    var index = 0;                          // The index where the element should be
    for( var key in array )                 // Iterate the array
    {
        if( parseInt( key ) !== index )     // If the element is out of sequence
        {
            array[index] = array[key];      // Move it to the correct, earlier position in the array
            ++index;                        // Update the index
        }
    }

    array.splice( index );  // Remove any remaining elements (These will be duplicates of earlier items)
},

당신은 이런 것을 사용할 수 있다.

var my_array = [1,2,3,4,5,6];
delete my_array[4];
console.log(my_array.filter(function(a){return typeof a !== 'undefined';})); // [1,2,3,4,6]

는 각 할 수 .delete 및 """splice()메서드가 적용됩니다.예를 들어 다음과 같습니다.

delete 연산자

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
delete trees[3];

console.log(trees); // ["redwood", "bay", "cedar", empty, "maple"]
console.log(trees.length); // 5

delete연산자는 요소를 배열에서 제거하지만 요소의 "플레이스홀더"는 여전히 존재합니다. oak는 삭제되었지만 어레이에 아직 공간이 남아 있습니다.5로 됩니다.

splice() 메서드

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
trees.splice(3,1);

console.log(trees); // ["redwood", "bay", "cedar", "maple"]
console.log(trees.length); // 4

splice()method를 사용하면 타겟 과 "플레이스 홀더"가 완전히 제거됩니다. oak어레이에서 사용하던 공간뿐만 아니라 제거되었습니다.네 번째

필터만 하면 되지?js의 어레이를 고려하는 가장 명확한 방법이라고 생각합니다.

myArray = myArray.filter(function(item){
    return item.anProperty != whoShouldBeDeleted
});

은 이미 했다.deletesplice.

또 다른 흥미로운 비교는deletevs 대 undefined: 은 방금 보다 적은 undefined;

예를 들어, 이 코드는 종료되지 않습니다.

let y = 1;
let ary = [];
console.log("Fatal Error Coming Soon");
while (y < 4294967295)
{
    ary.push(y);
    ary[y] = undefined;
    y += 1;
}
console(ary.length);

다음과 같은 에러가 발생합니다.

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory.

보시는 undefined실제로 히프 메모리를 사용합니다.

' '도'를 하는 경우에는 '''delete ary로 )undefined는,

let x = 1;
let ary = [];
console.log("This will take a while, but it will eventually finish successfully.");
while (x < 4294967295)
{
    ary.push(x);
    ary[x] = undefined;
    delete ary[x];
    x += 1;
}
console.log(`Success, array-length: ${ary.length}.`);

예이지만, 은 '일부러'나 '일부러'에 .delete그 누구도 언급한 적이 없는 것 같아요

성능

기능적인 차이에 대해서는 이미 많은 훌륭한 답변이 있습니다.여기에서는 퍼포먼스에 초점을 맞추고 싶습니다.오늘(2020.06.25) Chrome 83.0, Safari 13.1 및 Firefox 77.0에 대해 해당 솔루션을 테스트하고 선택한 답변에서 추가로 테스트합니다.

결론들

  • splice및 어레이에 대한 (B)
  • delete 어레이에 빅 및 (A)
  • filter어레이의 및 Safari에서는 에서는 더 느림). (E) Chrome 에 Firefox firefox 、 ( Safari ) 。
  • 솔루션 D는 매우 느리다.
  • C크롬 사파리 사파리 C크롬 사파리 C크롬 사파리 사파리 C크롬 사파리 C크롬 사파리 C크롬 사파리 C크롬 사파리 사파리 C크롬 사파리 C크롬 사파리 C크롬 사파리 C크롬 사파리 C크롬 사파리 사파리 사파리
    function C(arr, idx) {
      var rest = arr.slice(idx + 1 || arr.length);
      arr.length = idx < 0 ? arr.length + idx : idx;
      arr.push.apply(arr, rest);
      return arr;
    }
    
    
    // Crash test
    
    let arr = [...'abcdefghij'.repeat(100000)]; // 1M elements
    
    try {
     C(arr,1)
    } catch(e) {console.error(e.message)}

여기에 이미지 설명 입력

세부 사항

솔루션 A B C D E(my)에 대해 다음 테스트를 수행합니다.

  • 스몰 어레이 (4 요소)의 경우 - 여기서 테스트를 실행할 수 있습니다.
  • 빅 어레이 (100만 요소) - 여기에서 테스트를 실행할 수 있습니다.

function A(arr, idx) {
  delete arr[idx];
  return arr;
}

function B(arr, idx) {
  arr.splice(idx,1);
  return arr;
}

function C(arr, idx) {
  var rest = arr.slice(idx + 1 || arr.length);
  arr.length = idx < 0 ? arr.length + idx : idx;
  arr.push.apply(arr, rest);
  return arr;
}

function D(arr,idx){
    return arr.slice(0,idx).concat(arr.slice(idx + 1));
}

function E(arr,idx) {
  return arr.filter((a,i) => i !== idx);
}

myArray = ['a', 'b', 'c', 'd'];

[A,B,C,D,E].map(f => console.log(`${f.name} ${JSON.stringify(f([...myArray],1))}`));
This snippet only presents used solutions

Chrome 결과 예시

여기에 이미지 설명 입력

function remove_array_value(array, value) {
    var index = array.indexOf(value);
    if (index >= 0) {
        array.splice(index, 1);
        reindex_array(array);
    }
}
function reindex_array(array) {
   var result = [];
    for (var key in array) {
        result.push(array[key]);
    }
    return result;
}

예:

var example_arr = ['apple', 'banana', 'lemon'];   // length = 3
remove_array_value(example_arr, 'banana');

바나나가 삭제되고 배열 길이 = 2

그것들은 다른 목적을 가진 다른 것들입니다.

splice는 어레이 고유하며 삭제에 사용할 경우 어레이에서 엔트리를 삭제하고 이전 엔트리를 모두 이동하여 공백을 메웁니다(엔트리를 삽입하거나 동시에 삽입할 수도 있습니다). splice 바뀌게 .length : "no-op" (no-op) :theArray.splice(x, 0)를 참조해 주세요.

delete는 어레이 고유의 것이 아니라 오브젝트에서 사용하도록 설계되어 있습니다.속성(키/값 쌍)을 사용하는 개체에서 제거합니다.이는 JavaScript의 표준(비타이프형) 어레이는 실제로는 어레이*가 아니기 때문에 어레이에만 적용됩니다.이러한 어레이는 특정 속성(예를 들어 문자열 이름으로 정의됨)에 대해 특별한 처리를 하는 객체입니다.그 수치i +0 ≤ i < 2^32-1및 ") »length 「 」를 사용하는 delete어레이 엔트리를 삭제하려면 엔트리를 삭제하기만 하면 됩니다.다른 엔트리는 공백이 메워지지 않기 때문에 어레이는 "확장" 상태가 됩니다(일부 엔트리가 완전히 누락되어 있습니다.은 전혀 영향을 .length.

중 몇 .delete를 트리 the the the the the the " " " " the the " " 。undefined". 그렇지 않습니다.엔트리(속성)는 완전히 삭제되어 공백이 남습니다.

몇 가지 코드를 사용하여 차이점을 설명하겠습니다.

console.log("Using `splice`:");
var a = ["a", "b", "c", "d", "e"];
console.log(a.length);            // 5
a.splice(0, 1);
console.log(a.length);            // 4
console.log(a[0]);                // "b"

console.log("Using `delete`");
var a = ["a", "b", "c", "d", "e"];
console.log(a.length);            // 5
delete a[0];
console.log(a.length);            // still 5
console.log(a[0]);                // undefined
console.log("0" in a);            // false
console.log(a.hasOwnProperty(0)); // false

console.log("Setting to `undefined`");
var a = ["a", "b", "c", "d", "e"];
console.log(a.length);            // 5
a[0] = undefined;
console.log(a.length);            // still 5
console.log(a[0]);                // undefined
console.log("0" in a);            // true
console.log(a.hasOwnProperty(0)); // true


* (그건 빈혈 블로그에 올린 글이야)

현재 두 가지 방법이 있습니다.

  1. 스플라이스() 사용

    arrayObject.splice(index, 1);

  2. 삭제 사용

    delete arrayObject[index];

단, 삭제해도 어레이 길이가 갱신되지 않으므로 어레이 오브젝트에는 스플라이스를 사용하고 오브젝트 속성에는 삭제할 것을 항상 권장합니다.

다음 어레이가 있다고 가정해 보겠습니다.

const arr = [1, 2, 3, 4, 5];

먼저 삭제하겠습니다.

delete arr[1];

결과는 다음과 같습니다.

[1, empty, 3, 4, 5];

비었어! 그럼 시작하자:

arr[1]; //undefined

즉, 값이 삭제되고 현재 정의되지 않았기 때문에 길이가 같고 true가 반환됩니다.

이번에는 어레이를 리셋하고 스플라이스를 사용해 보겠습니다.

arr.splice(1, 1);

이번 결과는 다음과 같습니다.

[1, 3, 4, 5];

보시다시피 어레이의 길이가 변경되어 있습니다.arr[1]지금 3살...

인 한한어어 also in in in in in in in in in in in in in in in in in in가 됩니다.[3]이경...

어레이의 는, 「」를 사용할 수 .filter:

myArray = ['a', 'b', 'c', 'd'];
myArray = myArray.filter(x => x !== 'b');

두 가지 방법이 있습니다.

간단한 것:

arr = arr.splice(index,1)

두 번째:

arr = arr.filter((v,i)=>i!==index)

두 번째 인스턴스의 장점은 값을 삭제할 수 있다는 것입니다(대부분의 첫 번째 인스턴스뿐만 아니라 모두).

arr = arr.filter((v,i)=>v!==value)

가장 쉬운 방법은 아마도

var myArray = ['a', 'b', 'c', 'd'];
delete myArray[1]; // ['a', undefined, 'c', 'd']. Then use lodash compact method to remove false, null, 0, "", undefined and NaN
myArray = _.compact(myArray); ['a', 'c', 'd'];

이게 도움이 됐으면 좋겠다.참고 자료: https://lodash.com/docs#compact

Lodash를 사용하고자 하는 사용자는 다음을 사용할 수 있습니다.myArray = _.without(myArray, itemToRemove)

Angular2에서 사용하는 것처럼

import { without } from 'lodash';
...
myArray = without(myArray, itemToRemove);
...

delete: delete는 오브젝트 속성을 삭제하지만 어레이를 다시 인덱싱하거나 길이를 업데이트하지 않습니다.이것에 의해, 정의되어 있지 않은 것처럼 표시됩니다.

splice: 실제로 요소를 제거하고 배열을 다시 인덱싱하고 길이를 변경합니다.

마지막으로 요소 삭제

arrName.pop();

요소를 처음부터 삭제하다

arrName.shift();

중간에서 삭제

arrName.splice(starting index,number of element you wnt to delete);

Ex: arrName.splice(1,1);

마지막으로 요소 하나를 삭제합니다.

arrName.splice(-1);

배열 인덱스 번호를 사용하여 삭제

 delete arrName[1];

삭제할 요소가 중간에 있는 경우(예를 들어 인덱스가 1인 'c'를 삭제하려고 합니다), 다음을 사용할 수 있습니다.

var arr = ['a','b','c'];
var indexToDelete = 1;
var newArray = arr.slice(0,indexToDelete).combine(arr.slice(indexToDelete+1, arr.length))

IndexOf는 참조 유형도 받아들입니다.하다

var arr = [{item: 1}, {item: 2}, {item: 3}];
var found = find(2, 3); //pseudo code: will return [{item: 2}, {item:3}]
var l = found.length;

while(l--) {
   var index = arr.indexOf(found[l])
      arr.splice(index, 1);
   }
   
console.log(arr.length); //1

다른 점:

var item2 = findUnique(2); //will return {item: 2}
var l = arr.length;
var found = false;
  while(!found && l--) {
  found = arr[l] === item2;
}

console.log(l, arr[l]);// l is index, arr[l] is the item you look for

심플하게:-

배열에서 요소를 삭제하면 지정된 위치의 값이 삭제되고 비어 있거나 정의되지 않은 위치가 배열에 존재합니다.

var arr = [1, 2, 3 , 4, 5];

function del() {
  delete arr[3];
  console.log(arr);
}
del(arr);

여기서 인수는 splice 프로토타입과 같이 다음과 같습니다.//arr.splice(삭제할 항목의 번호, 삭제를 시작하는 위치)

var arr = [1, 2, 3 , 4, 5];

function spl() {
  arr.splice(0, 2);
// arr.splice(position to start the delete , no. of items to delete)
  console.log(arr);
}
spl(arr);

function deleteFromArray(array, indexToDelete){
  var remain = new Array();
  for(var i in array){
    if(array[i] == indexToDelete){
      continue;
    }
    remain.push(array[i]);
  }
  return remain;
}

myArray = ['a', 'b', 'c', 'd'];
deleteFromArray(myArray , 0);

// 결과 : myArray = ['b', 'c', 'd'];

언급URL : https://stackoverflow.com/questions/500606/deleting-array-elements-in-javascript-delete-vs-splice

반응형