浅拷贝: 如果属性是基本类型,拷贝的就是基本类型的值,如果属性是引用类型拷贝的就是内存地址,两个对象指向同一个地址。
深拷贝: 将对象里的所有数据重新复制到新的内存空间,是最彻底的拷贝。两个对象指向不同的地址
浅拷贝
在JS中存在浅拷贝的现象有
object.assign
Array.prototype.slice()
,Array.prototype.concat()
- 使用扩展运算符实现的复制
Object.assign()
将obj1拷贝给obj2,如果对象里的属性名相同,会被覆盖
obj2 = Object.assign(obj2, obj1)
Object.assign(target, 源对象1, 源对象2…)
//Object.assign()
var obj = {
age: 18,
nature: ['smart', 'good'],
names: {
name1: 'fx',
name2: 'xka'
},
love: function () {
console.log('fx is a great girl')
}
}
var newObj = Object.assign({}, fxObj);
newObj.names.name1 = 'lys'
console.log(obj.names,name1) //lys
//slice()
const fxArr = ["One", "Two", "Three"]
const fxArrs = fxArr.slice(0)
fxArrs[1] = "love";
console.log(fxArr) // ["One", "Two", "Three"]
console.log(fxArrs) // ["One", "love", "Three"]
//concat()
const fxArr = ["One", "Two", "Three"]
const fxArrs = fxArr.concat()
fxArrs[1] = "love";
console.log(fxArr) // ["One", "Two", "Three"]
console.log(fxArrs) // ["One", "love", "Three"]
//扩展运算符
const fxArr = ["One", "Two", "Three"]
const fxArrs = [...fxArr]
fxArrs[1] = "love";
console.log(fxArr) // ["One", "Two", "Three"]
console.log(fxArrs) // ["One", "love", "Three"]
深拷贝
深拷贝开辟一个新的栈,两个对象属性完全相同,但是对应不同两个地址,修改一个对象的属性,不会改变另一个对象的属性
常见的深拷贝方式
_.cloneDeep()
jQuery.extend()
JSON.stringify()
- 手写循环递归
_.cloneDeep()
const _ = require('lodash');
const obj1 = {
a: 1,
b: { f: { g: 1 } },
c: [1, 2, 3]
};
const obj2 = _.cloneDeep(obj1);
console.log(obj1.b.f === obj2.b.f);// false
jQuery.extend()
const $ = require('jquery');
const obj1 = {
a: 1,
b: { f: { g: 1 } },
c: [1, 2, 3]
};
const obj2 = $.extend(true, {}, obj1);
console.log(obj1.b.f === obj2.b.f); // false
JSON.stringify():但是会忽略undefined
、symbol
和函数
const obj2=JSON.parse(JSON.stringify(obj1));
循环递归
// 方法:深拷贝
function deepCopy(newObj, oldObj) {
for (let key in oldObj) {
// 获取属性值 oldObj[key]
let item = oldObj[key];
// 判断这个值是否是数组
if (item instanceof Array) {
newObj[key] = [];
deepCopy(newObj[key], item);
} else if (item instanceof Object) {
// 判断这个值是否是对象
newObj[key] = {};
deepCopy(newObj[key], item);
} else {
// 简单数据类型,直接赋值
newObj[key] = item;
}
}
小结
前提为拷贝类型为引用类型的情况下:
- 浅拷贝是拷贝一层,属性为对象时,浅拷贝是复制,两个对象指向同一个地址
- 深拷贝是递归拷贝深层次,属性为对象时,深拷贝是新开栈,两个对象指向不同的地址