javaScript - 对象的创建方式与遍历对象
1.使用对象字面量的方式:
var person1={ id: 1001, name: "levi", love: ["1","2","3"], say: function (arg){ console.log(arg) } } var id=person1.id; person1.say("你好");
2.使用Object 关键字方式来创建
var person2=new Object(); person2.id=1001; person2.name="levi"; person2.love=["1","2","3"]; person2.say=function (arg){ console.log(arg); } var id=person2.id; person2.say("你好");
3.用构造函数来创建
function person3(id,name,love) { this.id=id; this.name=name; this.love=love; this.say=function (arg){ console.log(arg); } } var human=new person3(1001,"levi",[1,2]); var id=human.id; human.say("你好");
遍历对象:
//遍历对象 for(var key in obj){ var key_name=key; var value=obj[key]; }