本文最后更新于 128 天前,其中的信息可能已经有所发展或是发生改变。
修改新对象原来的对象会发生改变(改变存储空间,联动改变)
let person = {
name: 'Tom',
age: 12,
hobby: ['音乐', '动漫']
}
let copyObj = person;
copyObj.name = '小明';
copyObj.hobby[0] = '看电视'
console.log(copyObj, person);
// { name: '小明', age: 12, hobby: [ '看电视', '动漫' ] } { name: '小明', age: 12, hobby: [ '看电视', '动漫' ] }
浅拷贝 基本类型直接拷贝值(新变原不变),引用类型拷贝内存地址(新变原变)
let person = {
name: 'Tom',
age: 12,
hobby: ['音乐', '动漫']
}
function shallowCopy(object) {
var target = {}
for (const key in object) {
if (object.hasOwnProperty(key)) {
target[key] = object[key]
}
}
return target
}
let copyObj = shallowCopy(person);
copyObj.name = '小红';
copyObj.hobby[0] = '看电影';
console.log(copyObj, person);
// { name: '小红', age: 12, hobby: [ '看电影', '动漫' ] } { name: 'Tom', age: 12, hobby: [ '看电影', '动漫' ] }
let person = {
name: 'Tom',
age: 12,
hobby: ['音乐', '动漫']
}
let copyObj = { ...person };
copyObj.age = '20';
copyObj.name = 'Jerry';
copyObj.hobby[0] = '看文学名著'
console.log(copyObj, person)
// { name: 'Jerry', age: '20', hobby: [ '看文学名著', '动漫' ] } { name: 'Tom', age: 12, hobby: [ '看文学名著', '动漫' ] }
深拷贝 新变原不变(在堆内存中开辟新的区域,修改不会影响原来的)
let person = {
name: 'Tom',
age: 12,
hobby: ['音乐', '动漫']
}
function deepClone(object) {
var cloneObj = Array.isArray(object) ? [] : {};
if (object === null) return object
if (object instanceof Date) return new Date(object)
if (object instanceof RegExp) return new RegExp(object)
if (typeof object !== 'object') return object
for (const key in object) {
if (object.hasOwnProperty(key)) {
cloneObj[key] = deepClone(object[key])
}
}
return cloneObj
}
let copyObj = deepClone(person);
copyObj.name = 'Marry';
copyObj.age = 18;
copyObj.hobby[0] = 'football';
console.log(copyObj, person);
// { name: 'Marry', age: 18, hobby: [ 'football', '动漫' ] } { name: 'Tom', age: 12, hobby: [ '音乐', '动漫' ] }
let obj = {
key: 1,
person: {
name: 'Marry',
age: 12
}
}
let copyObj = JSON.parse(JSON.stringify(obj));
copyObj.key = 2;
copyObj.person.name = 'Bob';
copyObj.person.age = 13;
console.log(copyObj,obj)
// { key: 2, person: { name: 'Bob', age: 13 } } { key: 1, person: { name: 'Marry', age: 12 } }
Object.assign()可实现深拷贝和浅拷贝(当只有一层时为深拷贝,两层及以上为浅拷贝)
let bookInfo = {
name: '西游记',
autor: '吴承恩',
sellstaus: '良好'
}
let person = {
name: 'Tom',
age: 12,
hobby: ['音乐', '动漫']
}
let copyObj1 = Object.assign({}, bookInfo);
let copyObj2 = Object.assign({}, person);
copyObj1.name = '红楼梦',
copyObj1.autor = '曹雪芹',
copyObj1.sellstaus = '中等'
copyObj2.name = '小明',
copyObj2.age = 22,
copyObj2.hobby[0] = 'basketball'
console.log(copyObj1, copyObj2)
// { name: '红楼梦', autor: '曹雪芹', sellstaus: '中等' } { name: '小明', age: 22, hobby: [ 'basketball', '动漫' ] }