删除操作符

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)