//空的对象实例
let user = new Object();
let user = {};
//带有属性的对象赋值
let user = {
name: "John",
age: 30
};
//查看属性
alert(user.name);
alert(user.age);
//给对象的属性赋值
user.isAdmin = true;
//删除对象的属性
delete uesr.age
第二种方法
let user = {
name: "John",
age: 30,
"likes birds": true
};
//使用数组索引的方法来添加属性的值
//访问属性的值
//删除属性的值
let user = {};
user['likes birds'] = true;
alert(user['likes birds']);
delete user['likes birds']
let fruit = 'apple';
let bag = {
[fruit + 'Computers']: 5
};
function makeUesr(name, age) {
return {
name: name,
age: age,
}
}
判断属性是否在对象之中
let user = {};
user.noSuchProperty === undefined
let user = { name:"John", age: 30};
alert("age" in user) //true user.age 存在
alert("blabla" in user) //false user.blabla 不存在
判断属性是否在对象之中
//测试age属性是否在user 之中
let user = { age:30 };
let key = "age";
alert(key in user);
let obj = {
test: undefined
};
alert(obj.test);
alert("test" in obj);
for (key in obj) {
alert( key );
alert( user[key] );
}
let salarires = {
John: 100,
Ann: 160,
Pete: 130
};
multiplyNumeric(obj)
let menu = {
width: 200,
height: 300,
title: "My menu"
};
let user = {
name: "John"
};
判断对象是否同引用
//复制引用 两个引用都指向同一个对象实例
let user = { name: "John" };
let admin = user;
//通过admin 可以对user.name的对象进行修改
admin.name = "Pete";
alert(user.name);
//通过引用来比较 同一对象
let a = {};
let b = a;
alert(a==b); //true 同一对象
alert(a===b); //true
let a = {};
let b = {};
alert(a==b);//false
克隆和拷贝
Object.assign
克隆与合并
let user = {
name: "John",
age: 30
};
let clone = {}; //新的对象
//将user的对象拷贝到clone对象之中
for (let key in user) {
clone[key] = user[key];
}
//改变clone对象中的数据, user对象之中仍然是原来的值
clone.name = "Pete";
alert(user.name);
//通过Object.assign方法实现
//Object.assign
let user = { name: "John"};
let permissions1 = { canView: true };
let permissions2 = { canEdit: true };
Object.assign(user, permission1, permissions2);
let user = {
name: "John",
age: 30
};
let clone = Object.assign({}, user);
深层克隆(深拷贝)
//深层克隆
let user = {
name: "John",
sizes: {
height: 182,
width: 50
}
};
alert(user.sizes.height);
let user = {
name: "John",
sizes: {
height: 182,
width: 50
}
};
let clone = Object.assign({}, user);
alert(user.sizes == clone.sizes );