转自:https://www.cnblogs.com/backpacker/archive/2012/08/01/2619180.html
Javascript 中可以动态添加 对象属性
<html> <head> <script type="text/javascript"> var obj = new Object(); alert (obj.username); obj.username = "allen"; alert (obj.username); </script> </head> <body> </body> </html>
结果:
依次打印出 undefined, allen
也可用类似 EL (Expression Language)那样用“[]”表示。写成 obj["username"] = "allen";
如何删除属性? 使用 delete
<html> <head> <script type="text/javascript"> var obj = new Object(); obj["username"] = "allen"; alert (obj.username); delete obj.username; alert (obj.username); </script> </head> <body> </body> </html>
结果:依次打印 allen, undefined. 说明 username 属性已经删除。
另外还有一种定义属性的方法,而且是我们必须掌握的:
<html> <head> <script type="text/javascript"> var obj = {username:"allen", password:"123"}; alert(obj.username); alert(obj.password); </script> </head> <body> </body> </html>
结果:allen, 123
这种方法是我们将来最常用的。必须掌握!