淺拷貝只復(fù)制指向某個(gè)對(duì)象的指針,而不復(fù)制對(duì)象本身,新舊對(duì)象還是共享同一塊內(nèi)存。
深拷貝:將 B 對(duì)象拷貝到 A 對(duì)象中,包括 B 里面的子對(duì)象,
淺拷貝:將 B 對(duì)象拷貝到 A 對(duì)象中,但不包括 B 里面的子對(duì)象
1.?JSON.parse(JSON.stringify(arr));
這種方法雖然可以實(shí)現(xiàn)數(shù)組或?qū)ο笊羁截?但不能處理函數(shù)
let arr = [1, 3, {
? ? username: ' kobe'
},function(){}];
let arr4 = JSON.parse(JSON.stringify(arr));
arr4[2].username = 'duncan';
console.log(arr, arr4)
2.遞歸&&判斷類型
? ? function extend(target, source, deep) {
? ? ? ? for (key in source)
? ? ? ? ? ? if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
? ? ? ? ? ? ? ? if (isPlainObject(source[key]) && !isPlainObject(target[key]))
? ? ? ? ? ? ? ? ? ? target[key] = {}
? ? ? ? ? ? ? ? if (isArray(source[key]) && !isArray(target[key]))
? ? ? ? ? ? ? ? ? ? target[key] = []
? ? ? ? ? ? ? ? extend(target[key], source[key], deep)? ? ? ? // 執(zhí)行遞歸
? ? ? ? ? ? }
? ? ? ? ? ? else if (source[key] !== undefined) target[key] = source[key]
? ? }