DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> JavaScript中對象property的刪除方法介紹
JavaScript中對象property的刪除方法介紹
編輯:關於JavaScript     

JavaScript中,可以使用delete操作符來刪除對象中的property:


復制代碼 代碼如下:
var t = {a:42, b:26};
console.log(t);//Object {a=42, b=26}
delete t.a;
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);
a.z = 3;
console.log(a);//Object {z=3, x=1, y=2}
delete a.x;//Can NOT delete inherited property
console.log(a);//Object {z=3, x=1, y=2}
delete a.z;//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錯誤。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved