经过验证,可以以后直接拿着使用的使用
function cloneDeep (source) {
if (!isObject(source)) {
return source;
}
var target = Array.isArray(source) ? [] : {};
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
if (isObject(source[key])) {
target[key] = cloneDeep2(source[key]);
} else {
target[key] = source[key];
}
}
}
return target;
}
验证
// 测试用例
var a = {
name: "muyiy",
book: {
title: "You Don't Know JS",
price: "45"
},
a1: undefined,
a2: null,
a3: 123
}
var arr = [
{
a: 123,
c: {v: 1}
},
{
a: 456,
c: {v: 2}
},
];
var b = cloneDeep(a);
var d = cloneDeep(arr);
a.name = 'i am s';
a.book.price = 1000;
console.log('b', b);
console.log('d', d);