对象定义的三种方式:
1 . var obj1 = {"name" : "张三"}
2 .var obj2 = new Object({name:"张三"});
3 . var obj3 = Object.create({name:"张三"});
var obj1 = {
name:"李四",
age:19,
};
直接定义对象
var obj1 = new Object({“name”:"张三"});
追加定义对象
var obj3 = new Object();
obj3.name = "张三";
obj3.age = "20";
覆盖定义对象;
obj3 = {
"height":"178cm",
hobby:function(){
console.log("爱好");
}
}
js对象的键名不需要双引号,json的键名需要双引号 规范外单内双
var json = '{"name":"张三","age":"19"}';
对象转换成json
var json1 = JSON.stringify(obj3);
json数据转换成对象
var json2 = JSON.parse(json1);
传值与传值
-
传值:
var a = 10; var b = a; b = 5; console.log(a);//10
-
传址:对象赋值取相同的内存地址;
var obj = { a:10 } var obj2 = obj; obj2.a = 5; console.log(obj.a);//5
深度拷贝;arr 和 arr2之间不会有联系
var arr = [1,2,3,4,5];
var arr2 = arr;
var arr2 = JSON.parse(JSON.stringify(arr));
arr2[2] = 7;
console.log(arr);
console.log(arr2);
对象属性和方法的调用
var dog = {
name:"wuli",
gender:"female",
eat:function(){
console.log("吃");
},
play:function(){
console.log("撒欢");
},
call:function(){
console.log("叫");
}
}
console.log(dog);
// 调用属性
console.log(dog.name);
// 调用方法
dog.eat();
dog.play();
dog.call();