标签:function desc 运算 key create foreach one ret type
1 使用对象和字符串的转换实现
function deepClone2(obj) { var obj = JSON.stringify(obj), objClone = JSON.parse(obj); return objClone; }
2 使用扩展运算符
// 深拷贝对象 var obj = {a: 1}, objClone = {...obj}; // 深拷贝数组 var arr = [1, 2], arrClone = {...arr};
3 Object.assign()
// 当对象中只有一级属性,没有二级属性的时候,此方法为深拷贝 // 但是对象中有对象的时候,此方法在二级属性就是浅拷贝 var obj = {a: 1}, objClone = Object.assign({}, obj);
4 递归实现
//使用递归的方式实现数组、对象的深拷贝 function deepClone(obj) { //判断拷贝的要进行深拷贝的是数组还是对象,是数组的话进行数组拷贝,对象的话进行对象拷贝 var objClone = Array.isArray(obj) ? [] : {}; //进行深拷贝的不能为空,并且是对象 if (obj && typeof obj === "object") { for (key in obj) { if (obj.hasOwnProperty(key)) { if (obj[key] && typeof obj[key] === "object") { objClone[key] = deepClone1(obj[key]); } else { objClone[key] = obj[key]; } } } } return objClone; }
5 使用Object.create()实现
function deepCopy(obj) { var copy = Object.create(Object.getPrototypeOf(obj)); var propNames = Object.getOwnPropertyNames(obj); propNames.forEach(function(name) { var desc = Object.getOwnPropertyDescriptor(obj, name); Object.defineProperty(copy, name, desc); }); return copy; } var obj1 = { a: 1, b: {bc: 50, dc: 100, be: {bea: 1}} }; var obj2 = deepCopy(obj1); console.log(obj2) obj1.a = 20; console.log(obj1) console.log(obj2) //Object {a: 1, b: Object} //Object {a: 20, b: Object} //Object {a: 1, b: Object}
原文:https://blog.csdn.net/chentony123/article/details/81428803
https://segmentfault.com/a/1190000018371840
标签:function desc 运算 key create foreach one ret type
原文地址:https://www.cnblogs.com/xjy20170907/p/12672852.html