Reflect.deleteProperty()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2016.

Phương thức tĩnh Reflect.deleteProperty() giống như toán tử delete, nhưng dưới dạng hàm. Nó xóa một thuộc tính khỏi một đối tượng.

Try it

const object = {
  foo: 42,
};

Reflect.deleteProperty(object, "foo");

console.log(object.foo);
// Expected output: undefined

const array = [1, 2, 3, 4, 5];
Reflect.deleteProperty(array, "3");

console.log(array);
// Expected output: Array [1, 2, 3, <1 empty slot>, 5]

Cú pháp

js
Reflect.deleteProperty(target, propertyKey)

Tham số

target

Đối tượng target trên đó xóa thuộc tính.

propertyKey

Tên của thuộc tính cần xóa.

Giá trị trả về

Một boolean cho biết thuộc tính có được xóa thành công hay không.

Ngoại lệ

TypeError

Được ném ra nếu target không phải là đối tượng.

Mô tả

Reflect.deleteProperty() cung cấp ngữ nghĩa phản chiếu của toán tử delete. Tức là, Reflect.deleteProperty(target, propertyKey) tương đương về mặt ngữ nghĩa với:

js
delete target.propertyKey;

Ở mức độ rất thấp, việc xóa thuộc tính trả về một boolean (như trường hợp của proxy handler). Reflect.deleteProperty() trả về trực tiếp trạng thái đó, trong khi delete sẽ ném ra TypeError trong strict mode nếu trạng thái là false. Trong non-strict mode, deleteReflect.deleteProperty() có cùng hành vi.

Reflect.deleteProperty() gọi phương thức nội tại [[Delete]] của đối tượng trên target.

Ví dụ

Sử dụng Reflect.deleteProperty()

js
const obj = { x: 1, y: 2 };
Reflect.deleteProperty(obj, "x"); // true
console.log(obj); // { y: 2 }

const arr = [1, 2, 3, 4, 5];
Reflect.deleteProperty(arr, "3"); // true
console.log(arr); // [1, 2, 3, <1 empty slot>, 5]

// Returns true if no such property exists
Reflect.deleteProperty({}, "foo"); // true

// Returns false if a property is unconfigurable
Reflect.deleteProperty(Object.freeze({ foo: 1 }), "foo"); // false

Đặc tả kỹ thuật

Specification
ECMAScript® 2027 Language Specification
# sec-reflect.deleteproperty

Tương thích trình duyệt

Xem thêm