Javascript/개념

[JS - 개념] delete

개발자성장기 2022. 7. 3. 23:32
반응형

 

delete 는 객체의 속성을 제거 할때 쓰는 연산자이다 

 

-반환값은 제거에 성공하면 true 실페하면 false  / stric 모드에서 속성이 자신의 속성이며 설정이 불가능할 경우 typeError

 

-delete는 단순히 객체와 속성과의 연결을 끊을 뿐 실제로 메모리에서 제거하는것은 아니다. 

 

-delete 하고 싶은 delete 연산자를 사용하기보다 값을 null 이나 undefined로 설정하는것을 추천한다.

 

var array = [0, 1, 2, 3]
delete array[2] 
true
array // (4) [0, 1, empty, 3]

(배열도 객체의 일종이기에 객체 및 배열에서 속성을 제거할때 사용가능)

 

 

- delete 연산을 하여도 배열의 크기는 그대로 유지 된다.

따라서 delete 연산은 배열을 재배치하여 돌려주는 연산자가 아니다. 

단지 hashmap 에서 key가 삭제 되는것은 아니라서 

for in 루프 / forEach / hasOwnProperty() 같이  key의 존재를 체크하는 경우에는 key가 드러난다.

 

for (var i = 0; i < array.length ; i++){ 
	console.log(array[i]) // 0 1 undefined 3
}
for (const key in array) { 
	console.log(key) // 0 1 3
}
for (const key of array) { 
	console.log(key) // 0 1 undefined 3
}
array.forEach(function(element){
	console.log(element); // 0 1 3
    });

 

따라서 확실히 메모리에서 제거하고 배열의 크기까지 반영되게 할려면 splice를 사용하는 것을 추천한다.

 

 

 

주의 : 삭제를 하면 true 반환, 아니면 false를 반환

  •   var로 선언된 어떠한 프로퍼티라도 글러벌 스코프나 펑션 스코프로부터 삭제될 수 없다.
  •  let과 const로 선언한 속성은 어느 스코프에 정의되어 있건 삭제 할 수 없다.         
  •  만약 존재하지 않는 속성을 삭제하려고 하면 delete는 어떠한 작업도 없이 true를 반환합니다. 
var Employee = {
  age: 28,
  name: 'abc',
  designation: 'developer'
}

console.log(delete Employee.name);   // returns true
console.log(delete Employee.age);    // returns true

// 존재하지 않는 속성을 삭제하려하면
// true를 리턴합니다.
console.log(delete Employee.salary); // returns true
var nameOther = 'XYZ';

// 우리는 이를 사용해 글로벌 속성에 접근 할 수 있습니다:
Object.getOwnPropertyDescriptor(window, 'nameOther');

// output: Object { value: "XYZ",
//                  writable: true,
//                  enumerable: true,
//                  configurable: false }

// "nameOther"은 var로 선언되었기 때문에
// 이는 "non-configurable" 속성으로 구분됩니다.

delete nameOther;   // return false
반응형