메소드 를 사용 하는 것과 반대로 배열 요소 에서 delete
연산자 를 사용 하는 것의 차이점은 무엇입니까 ?Array.splice
예를 들면 다음과 같습니다.
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
실제로 value로 설정되지 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”, “undefined”, “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"]
답변
에서 코어 자바 스크립트 1.5 참조> 연산자> 특수 연산자> 삭제 운영자 :
배열 요소를 삭제해도 배열 길이는 영향을받지 않습니다. 예를 들어, a [3]을 삭제하면 a [4]는 여전히 a [4]이고 a [3]은 정의되지 않습니다. 이것은 배열의 마지막 요소를 삭제하더라도 유지됩니다 (delete a [a.length-1]).
답변
splice
숫자 인덱스와 함께 작동합니다.
반면, delete
인덱스의 다른 종류에 대해 사용될 수있다 ..
예:
delete myArray['text1'];
답변
스플 라이스는 배열에서만 작동한다는 점도 언급 할 가치가 있습니다. (일관된 순서를 따르기 위해 객체 속성에 의존 할 수 없습니다.)
객체에서 키-값 쌍을 제거하려면 실제로 원하는 것이 delete입니다.
delete myObj.propName; // , or:
delete myObj["propName"]; // Equivalent.