js对象操作常用方法
一、创建对象
1.字面量创建
//字面量创建
let obj = {a:1}
2.构造函数创建
//构造函数创建
function Person(name,age){
this.name = name;
this.age = age;
}
let person = new Person('Bob',12);
二、访问对象属性
1.点符号
let obj = {a:1}
obj.a
2.方括号
let obj = {a:1}
obj['a'] //1
三、添加属性
obj.c = 3;
obj['d'] = 4;
四、删除属性
delete obj.a
五、判断属性是否存在
1.in运算符
let obj = {a:1,b:2}
'a' in obj //true
2.hasOwnProperty方法
obj.hasOwnProperty('a'); // true
六、遍历对象属性
1.for...in...循环
for (let prop in obj) {
if (obj.hasOwnProperty(prop)) {
console.log(`Key: ${prop}, Value: ${obj[prop]}`);
}
}
2.Object.keys,Object.values,Object.entries
Object.keys(obj).forEach(key => console.log(key));
Object.values(obj).forEach(value => console.log(value));
Object.entries(obj).forEach(([key, value]) => console.log(`${key}: ${value}`));
七、深拷贝与浅拷贝
1.浅拷贝
let obj = {a:1}
let shallowCopy = Object.assign({},obj)
2.深拷贝
let obj = {a:1}
let deepCopy = JSON.parse(JSON.stringify(obj))
八、合并对象
Object.assign
let obj2 = { e: 5 };
let merged = Object.assign({}, obj, obj2);
九、其他方法
1.Object.is() 比较两个值是否严格相等
Object.is(obj, obj); // true
2.Object.defineProperty() 定义或修改属性,并返回该对象
let obj = {}
Object.defineProperty(obj, 'f', { value: 6, writable: true, enumerable: true, configurable: true });
console.log(obj) //{f:6}