1.深拷贝对象或者数组
// 深拷贝对象
let person = {name:'小王',age:19}
let son = {...person} // {name:'小王',age:19}
//深拷贝数组
let arr = [1,2,3,4]
let arr1 = [...arr] // 1234
2.合并对象或者数组
let name = {name:'隔壁老王'}
let age = {age: 18}
let person = {...name,...age} // {name:'隔壁老王',age:18}
let arr = [1,2,3]
let arr1 = [...arr,4,5,6] // 1,2,3,4,5,6
3.对象的基本方法
- Object.assign() 对象的合并,浅拷贝主要应用target对象的值
let target = {x: 1, y: 2}
let source = {x: 3, z: 4}
let obj = Object.assign(target, source)
// {x: 3, y: 2, z: 4}
- Object.create() 创建对象,设置对象的属性
let obj = Object.create({x: 1, y: 2}, {
z: {
writable: true, // 是否可读写
configurable: true, // 是否可删除
value: 'jack',
enumerable: true // 是否可枚举
}
})
// {z: 'jack'} x, y 在obj的__proto__ 上
3.Object.defineProperties(obj,{}) 定义新的属性或者修改属性,并返回该对象
let obj = {x: 1}
Object.defineProperties(obj,{
y: {
value: 2,
writable: false
}
})
// {x: 1, y: 2}
- Object.defineProperty(obj, prop, options) 参考 3 prop:对象属性
5… Object.keys(obj) 返回可枚举的属性名 返回数组
let obj = {foo: 'apple', bar: '40'}
Object.keys(obj)
// ['foo', 'bar']
- Object.values(obj) 返回可枚举的属性值返回数组
Object.values(obj)
// ['apple','40']
- Object.entries(obj) // 返回可枚举的键值对数组
Object.entries(obj)
// [['foo','apple'],['bar','40']]
8.obj.hasOwnProperty() 判断对象自身属性中是否存在指定的属性
obj.hasOwnProperty('foo') // true
9.Object.getOwnPropertyNames() 返回对象的属性名 不包括symbol
Object.getOwnPropertyNames(obj)
//["foo", "bar"]
10.Object.is(obj,obj1) true 判断两个对象是否相等
注:必须是浅拷贝的对象才想等
let obj = {age: 18}
let obj1 = {...obj}
let obj2 = obj;
Object.si(obj,obj1) // false
Object.is(obj,obj2) // true
11.Object.freeze(obj) 冻结obj对象, 不可读写删除循环
12.Object.isFrozen(obj) 判断一个对象是否被冻结
13.Object.preventExtensions(obj) 对象不能新增属性,可删除修改
14.Object.setPrototypeOf(obj, prototype) 设置对象的原型
var obj = {x:1, y: 2}
var obj1 = {x: 4, z: 3}
Object.setPrototypeOf(obj, obj1)
// {x: 1, y: 2 } __proto__ {x: 4, z: 3}
15.isPrototypeOf 判断一个对象是否存在另一个对象的原型链上
obj1.isPrototypeOf(obj) // true