JavaScript中對象property的刪除方法介紹_javascript技巧

來源:互聯網
上載者:User

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,那麼在strict 模式下會報TypeError錯誤,而在非strict 模式下則返回false。
如果delete操作符所作用的是全域對象的property,那麼在非strict 模式下,代碼中的全域對象可以省略:

複製代碼 代碼如下:

this.c = 42;
delete c;//equal to delete this.c;

需要注意的是,在strict 模式下,上述寫法會拋SyntaxError錯誤。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.