实现 js 深度克隆
// 克隆一个obj
var obj = {
name: "abc",
age: 12,
card: ["visa", "master"],
wife: {
name: "zhang",
sun: {
name: "aaa"
}
}
}
var obj1 = {};
// 遍历对象 for(var prop in obj)
// 1. 判断是不是原始值 typeof() object
// 2. 判断是数组还是对象 toString instanceof constructor
// 3. 建立相应的数组或对象
// 递归
function deepClone(origin, target) {
var target = target || {},
toStr = Object.prototype.toString,
arrStr = "[object Array]";
for(var prop in origin) {
if(origin.hasOwnProperty(prop)) {
if(origin[prop] !== "null" && typeof (origin[prop]) == 'object') {
target[prop] = toStr.call(origin[prop]) == arrStr ? [] : {}
deepClone(origin[prop], target[prop])
}else{
target[prop] = origin[prop]
}
}
}
return target;
}
deepClone(obj, obj1); // 克隆
console.log(obj1);
执行结果如下:
image.png
网友评论