刪除操作符

delete 運算子從物件中刪除屬性。

句法:

delete object.property

delete object['property']

返回:

如果刪除成功,或該屬性不存在:

  • true

如果要刪除的屬性是自己的不可配置屬性(無法刪除):

  • false 處於非嚴格模式。
  • 在嚴格模式下引發錯誤

描述

delete 運算子不直接釋放記憶體。如果操作意味著對屬性的所有引用都消失了,它可以間接釋放記憶體。

delete 適用於物件的屬性。如果物件的原型鏈上存在具有相同名稱的屬性,則該屬性將從原型繼承。
delete 不適用於變數或函式名稱。

例子:

// Deleting a property
foo = 1;              // a global variable is a property of `window`: `window.foo`
delete foo;           // true
console.log(foo);     // Uncaught ReferenceError: foo is not defined

// Deleting a variable
var foo = 1;
delete foo;           // false
console.log(foo);     // 1 (Not deleted)

// Deleting a function
function foo(){ };
delete foo;           // false
console.log(foo);     // function foo(){ } (Not deleted)

// Deleting a property
var foo = { bar: "42" };
delete foo.bar;       // true
console.log(foo);     // Object { } (Deleted bar)

// Deleting a property that does not exist
var foo = { };
delete foo.bar;       // true
console.log(foo);     // Object { } (No errors, nothing deleted)

// Deleting a non-configurable property of a predefined object
delete Math.PI;       // false  ()
console.log(Math.PI); // 3.141592653589793 (Not deleted)