function deepClone(initalObj, finalObj) {
var obj = finalObj || {};
for (var i in initalObj) {
var prop = initalObj[i]; // 避免相互引用對象致使死循環,如initalObj.a = initalObj的狀況
if (prop === obj) {
continue;
}
if (typeof prop === 'object') {
obj[i] = (prop.constructor === Array) ? [] : {};
arguments.callee(prop, obj[i]); // 調用自身
} else {
obj[i] = prop;
}
}
return obj;
}
let initialObj = { a: '1', b: { name: { first: 'bob', last: 'zhou' }, age: 10 } }
let myObj = deepClone(initialObj)
console.log(myObj)
initialObj.b.name.first = 'chris'
console.log(initialObj)
console.log(myObj)
從打印結果能夠看出 拷貝的對象不會被改變對象
3>> 單層拷貝blog
object.assign() 遞歸
{...obj} string
這兩種都是單層深拷貝, 意思就是{age:10,name:'bob'}這種能夠深拷貝 it
{name:{first:'lily',last:'zhang'}}針對這種內層的不會被深拷貝 仍是拷貝其引用io