要求:
(1)对象属性可能是函数; (2)不需要拷贝原型链上的属性和方法;
直接上代码
let obj
= {
a
: [1, { ss
: "ss" }, [3], 4, 5, ["sad", "123", true]],
age
: 10,
name
: "老八",
eat
: "秘制小汉堡",
show
: {
skill
: "鸡你太美",
b
: function() {
console
.log(this.a
);
},
},
};
function cloneDeep(obj
) {
if (Array
.isArray(obj
) || typeof obj
=== "object") {
let cloneObj
= Array
.isArray(obj
) ? [] : {};
Object
.keys(obj
).forEach(function(key
) {
if (Array
.isArray(obj
[key
]) || typeof obj
[key
] === "object") {
cloneObj
[key
] = cloneDeep(obj
[key
]);
} else {
cloneObj
[key
] = obj
[key
];
}
});
return cloneObj
;
} else {
return obj
;
}
}
let cloneObj
= cloneDeep(obj
);
console
.log(cloneObj
);
cloneObj
.show
.skill();
有问题请大家交流指正
转载请注明原文地址:https://tech.qufami.com/read-16817.html