1.递归
function deepCopy(a) {
let cloned = Array.isArray(a)? [] : {};
if(a && typeof a === "object") {
for (let i in a) {
if(a.hasOwnProperty(i)) {
if(a[i] && typeof a[i] === "object") {
cloned[i] = deepCopy(a[i])
} else {
cloned[i] = a[i]
}
}
}
}
return cloned
}
let a = [1,2,3]
b = deepCopy(a)
a[0] = 2
console.log(a,b); // [2, 2, 3] [1, 2, 3]
let obj = {
a: { aa: 2},
b: 1
}
let objCp = deepCopy(obj);
obj.a.aa = 100;
console.log(objCp); // {a: {aa: 2}, b:1}
2.json
// 无法实现对对象中方法的深拷贝,会显示为undefined
function deepClone(obj) {
var _obj = JSON.stringify(obj),
objClone = JSON.parse(_obj);
return objClone;
}
3.通过jQuery的extend方法实现深拷贝
var array = [1,2,3,4];
var newArray = $.extend(true,[],array); // true为深拷贝,false为浅拷贝
4.lodash函数库实现深拷贝
let result = _.cloneDeep(test)
5.Reflect法
// 代理法
function deepClone(obj) {
if (!isObject(obj)) {
throw new Error('obj 不是一个对象!')
}
let isArray = Array.isArray(obj)
let cloneObj = isArray ? [...obj] : { ...obj }
Reflect.ownKeys(cloneObj).forEach(key => {
cloneObj[key] = isObject(obj[key]) ? deepClone(obj[key]) : obj[key]
})
return cloneObj
}
6.slice实现数组的深拷贝
// 当数组里面的值是基本数据类型,比如String,Number,Boolean时,属于深拷贝
// 当数组里面的值是引用数据类型,比如Object,Array时,属于浅拷贝
var arr1 = ["1","2","3"];
var arr2 = arr1.slice(0);
arr2[1] = "9";
console.log("数组的原始值:" + arr1 );
console.log("数组的新值:" + arr2 );