js使用递归来进行深拷贝
function deepClone(origin, target) {
var target = target || {};
var toStr = Object.prototype.toString;
var arrStr = "[object Array]";
for (var prop in origin) {
//判断是自身的属性
if (origin.hasOwnProperty(prop)) {
//判断是引用数据类型还是 原始数据类型
if (origin[prop] !== null && typeof (origin[prop]) === "object") {
//判断是数组还是对象
if (toStr.call(origin[prop]) === arrStr) {
//数组
target[prop] = []
} else {
//对象
target[prop] = {}
}
deepClone(origin[prop], target[prop]);
} else {
//原始数据类型
target[prop] = origin[prop];
}
}
}
//如果没有传入第二个参数 给返回target
return target;
}
使用例子:
var me = {
name: "xiaoming",
gender: "male",
feature: ["handsome", "young", "hardworking"],
address: {
city: "chengdu",
postcode: "610000",
},
girlFriend: {
name: "xiaoli",
gender: "female",
feature: ["beauty", "cute"],
address: {
city: "chengdu",
postcode: "610000",
}
}
};
var me2 = {};
deepClone(me, me2);
版权声明:
作者:东明兄
链接:https://blog.crazyming.com/note/547/
来源:CrazyMing
文章版权归作者所有,未经允许请勿转载。
THE END
二维码
海报
js使用递归来进行深拷贝
js使用递归来进行深拷贝 深度克隆
CrazyMing