深拷贝
Posted 郭郭郭牧鑫
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了深拷贝相关的知识,希望对你有一定的参考价值。
深拷贝:拷贝值
浅拷贝: 拷贝地址
1.json方式
var eeee= {
xiaoming: {
age: 20,
green: 150
},
xiaohong: {
age: 21,
green: 250
}
};
let yyk= JSON.stringify(eeee);//转换为json字符串形式
let result = JSON.parse(yyk);//转换为js对象
eeee.xiaoming.age=21
console.log(eeee.xiaoming.age);
console.log(result.xiaoming.age);
//两个不相等
2.运用for...in,递归方法进行深度拷贝
//1 .原生的方法写深度拷贝
function deepClone(obj) {
// 先判断是数组还是对象
var params = Array.isArray(obj) ? [] : {};
for (key in obj) {
if (obj[key] && typeof obj[key] == "object") {
params[key] = deepClone(obj[key]);
} else {
params[key] = obj[key];
}
}
return params;
}
var one = {
name: "hhhhh",
obj: {
title: "zzz"
},
};
var two = deepClone(one);
one.obj.title= "哈哈";
console.log(one);
console.log(two);
3.第三方插件Lodash实现深拷贝(方便)
<script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
var a = {
name: "我是a中的数据",
obj: {
name: "张三",
age: "40",
},
};
var b = _.cloneDeep(a, {
obj: {
name: "李四",
age: "50",
sex: "男",
},
});
a.obj.name = "王二";
console.log(a);
console.log(b);
4.利用数组的Array.prototype.forEach进copy
var deepClone = function (obj) {
let caa = Object.create(Object.getPrototypeOf(obj));
let propNames = Object.getOwnPropertyNames(obj);
propNames.forEach(function (items) {
let item = Object.getOwnPropertyDescriptor(obj, items);
Object.defineProperty(caa, items, item);
});
return copy;
};
var aaaaa = {
name: "kkk",
age: 22,
family: {mother: "kok", father: "kokdd"}
}
let bbb= deepClone(aaaaa);
console.log(bbb);
以上是关于深拷贝的主要内容,如果未能解决你的问题,请参考以下文章