如何在 JavaScript 中删除对象的属性?
如果要删除对象的属性,应使用 delete 关键字。Delete 关键字可与两种方法结合使用,例如 Dot 方法和 Bracket 方法。
语法
delete object.property;
示例
在以下示例中,最初执行属性“country”时,它的值“England”会显示在输出中。但是,当使用 delete 关键字删除该属性时,输出中会显示“undefined”,而不是“England”。
<html> <body> <script> var txt = ""; var person = { "name":"Ram", "age":27, "address": { "houseno" : 123, "streetname" : "Baker street", "country": "England" } } document.write("Before deletion :" + " "+ person.address.country); delete person.address.country; document.write("</br>"); document.write("After deletion :" + " "+ person.address.country); </script> </body> </html>
输出
Before deletion : England After deletion : undefined
广告