JavaScript中,可以使用delete操作符來刪除對像中的property:
複製代碼代碼如下:
var t = {a:42, b:26};
console.log(t);//Object {a=42, b=26}
delete ta;
console.log(t);//Object {b=26}
這種property刪除操作的局限性在於:delete操作符只能刪除對象自身所有的property,無法刪除其從prototype對象處繼承而來的property。如果想刪除prototype對像中的property,必須顯式獲取prototype對像後,在prototype對像中進行操作:
複製代碼代碼如下:
var o = {x:1, y:2};
var a = Object.create(o);
az = 3;
console.log(a);//Object {z=3, x=1, y=2}
delete ax;//Can NOT delete inherited property
console.log(a);//Object {z=3, x=1, y=2}
delete az;//Can delete own property
console.log(a);//Object {x=1, y=2}
delete a.__proto__.x;
console.log(a);//Object {y=2}
如果刪除了prototype對像中的property,那麼所有從該prototype對像中繼承的對像都會收到影響。
對於delete操作的返回值,JavaScript中遵循以下規則:
1.如果delete操作成功,返回true。
2.如果delete操作無任何效果(比如要刪除的property並不存在),也返回true。
3.如果要delete的property,其configurable屬性為false,那麼在嚴格模式下會報TypeError錯誤,而在非嚴格模式下則返回false。
如果delete操作符所作用的是全局對象的property,那麼在非嚴格模式下,代碼中的全局對象可以省略:
複製代碼代碼如下:
this.c = 42;
delete c;//equal to delete this.c;
需要注意的是,在嚴格模式下,上述寫法會拋SyntaxError錯誤。