Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Xóa property của object trong JavaScript

Dùng từ khóa delete — cách duy nhất thực sự xóa property khỏi object.

Cú pháp

delete object.property;
// hoặc
delete object['property']; // Bracket notation — key có ký tự đặc biệt hoặc biến

Ví dụ cơ bản

<script>
  const person = {
    name: 'Ram',
    age: 27,
    address: {
      houseNo: 123,
      street: 'Baker Street',
      country: 'England'
    }
  };

  document.write('Trước xóa: ' + person.address.country + '<br>'); // England

  delete person.address.country;

  document.write('Sau xóa: ' + person.address.country); // undefined
</script>

Đặc điểm quan trọng

  • Trả về true nếu xóa thành công hoặc property không tồn tại.
  • Trả về false chỉ khi property là non-configurable (strict mode throw TypeError).
  • Không ảnh hưởng prototype chain — chỉ xóa own property.
  • Property bị xóa: 'prop' in obj trả về false, obj.prop trả về undefined.

Khác với gán undefined/null

Lưu ý hiệu suất

  • delete làm chậm object trong V8 (hidden class transition) — tránh dùng trong hot path/high-frequency code.
  • Nếu cần xóa nhiều property thường xuyên: cân nhắc dùng Map (có delete() tối ưu) hoặc gán undefined + filter khi serialize.

Xóa property lồng nhau (nested)

delete person.address.country; // Dot notation
delete person['address']['country']; // Bracket notation
delete person.address['country']; // Mixed
CáchProperty còn tồn tại?'key' in objEnumerable?
delete obj.keyKhôngfalseKhông
obj.key = undefinedCótrueCó
obj.key = nullCótrueCó