試一試
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]
語法
js
Reflect.deleteProperty(target, propertyKey)
引數
目標-
要刪除屬性的目標物件。
propertyKey-
要刪除的屬性的名稱。
返回值
一個布林值,指示屬性是否已成功刪除。
異常
TypeError-
如果
target不是一個物件,則丟擲。
描述
Reflect.deleteProperty() 提供了 delete 運算子的反射語義。也就是說,Reflect.deleteProperty(target, propertyKey) 在語義上等同於
js
delete target.propertyKey;
在非常底層的級別,刪除屬性會返回一個布林值(正如 Proxy 的 handler 的情況)。Reflect.deleteProperty() 直接返回狀態,而在 嚴格模式下,如果狀態為 false,delete 會丟擲 TypeError。在非嚴格模式下,delete 和 Reflect.deleteProperty() 的行為相同。
Reflect.deleteProperty() 呼叫 target 的 [[Delete]] 物件內部方法。
示例
使用 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
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-reflect.deleteproperty |
瀏覽器相容性
載入中…