詳解JS深拷貝與淺拷貝
一、預(yù)備知識(shí)
1.1、JS數(shù)據(jù)類型
基本數(shù)據(jù)類型:Boolean、String、Number、null、undefined
引用數(shù)據(jù)類型:Object、Array、Function、RegExp、Date等
1.2、數(shù)據(jù)類型的復(fù)制
基本數(shù)據(jù)類型的復(fù)制,是按值傳遞的
var a = 1; var b = a; b = 2; console.log(a); // 1 console.lob(b); // 2
引用數(shù)據(jù)類型的復(fù)制,是按引用傳值
var obj1 = {
a: 1;
b: 2;
};
var obj2 = obj1;
obj2.a=3;
console.log(obj1.a); //3
console.log(obj2.a); // 3
1.3、深拷貝與淺拷貝
深拷貝和淺拷貝都只針對(duì)引用數(shù)據(jù)類型,淺拷貝會(huì)對(duì)對(duì)象逐個(gè)成員依次拷貝,但只復(fù)制內(nèi)存地址,而不復(fù)制對(duì)象本身,新舊對(duì)象成員還是共享同一內(nèi)存;深拷貝會(huì)另外創(chuàng)建一個(gè)一模一樣的對(duì)象,新對(duì)象跟原對(duì)象不共享內(nèi)存,修改新對(duì)象不會(huì)改到原對(duì)象。
區(qū)別:淺拷貝只復(fù)制對(duì)象的第一層屬性,而深拷貝會(huì)對(duì)對(duì)象的屬性進(jìn)行遞歸復(fù)制。
二、JS淺拷貝
2.1、賦值與淺拷貝
當(dāng)把一個(gè)對(duì)象賦值給一個(gè)新的變量時(shí),賦的對(duì)象是該對(duì)象在棧中的地址,而不是堆中的數(shù)據(jù)。也就是新舊兩個(gè)對(duì)象指的是同一個(gè)存儲(chǔ)空間,無論哪個(gè)對(duì)象發(fā)生改變,其實(shí)都是改變的存儲(chǔ)空間的內(nèi)容,兩個(gè)對(duì)象聯(lián)動(dòng)的會(huì)一起改變。
var obj1 = {
'name' : 'zhangsan',
'language' : [1,[2,3],[4,5]],
};
var obj2 = obj1;
obj2.name = "lisi";
obj2.language[1] = ["二","三"];
console.log('obj1',obj1)
console.log('obj2',obj2)

淺拷貝是按位拷貝對(duì)象,它會(huì)創(chuàng)建一個(gè)新對(duì)象,對(duì)原有對(duì)象的成員進(jìn)行依次拷貝。如果屬性是基本類型,拷貝的就是基本類型的值;如果屬性是引用類型,拷貝的就是內(nèi)存地址。因此如果新對(duì)象中的某個(gè)對(duì)象成員改變了地址,就會(huì)影響到原有的對(duì)象。
//手寫淺拷貝
function shallowCopy(obj1) {
let obj2 = Array.isArray(obj1) ? [] : {}
for (let i in obj1) {
obj2[i] = obj1[i]
}
return obj2
}
var obj1 = {
'name' : 'zhangsan',
'language' : [1,[2,3],[4,5]],
};
var obj2 = shallowCopy(obj1);
obj2.name = "lisi";
obj2.language[1] = ["二","三"];
console.log('obj1',obj1)
console.log('obj2',obj2)

2.2、淺拷貝的實(shí)現(xiàn)
(1)Object.assign()
Object.assign()方法可以把源對(duì)象自身的任意多個(gè)的可枚舉屬性拷貝給目標(biāo)對(duì)象,然后返回目標(biāo)對(duì)象,但是Object.assign()進(jìn)行的是淺拷貝,拷貝的是對(duì)象的屬性的引用,而不是對(duì)象本身。此方法對(duì)于Array和Object均可適用。
var obj1 = {
'name' : 'zhangsan',
'language' : [1,[2,3],[4,5]],
};
var obj2 = Object.assign({}, obj1);
obj2.name = "lisi";
obj2.language[1] = ["二","三"];
console.log('obj1',obj1)
console.log('obj2',obj2)

(2)Array.prototype.concat()和Array.prototype.slice()
Array.prototype.concat()和Array.prototype.slice()均為Array原型上的方法,只適用于Array。
var arr1 = [1,3,{
user: 'aaa'
}]
var arr2 = arr1.concat();
arr2[0] = '一';
arr2[2].user = 'AAA';
console.log('arr1',arr1)
console.log('arr2',arr2)
var arr1 = [1,3,{
user: 'aaa'
}]
var arr2 = arr1.slice();
arr2[0] = '一';
arr2[2].user = 'AAA';
console.log('arr1',arr1)
console.log('arr2',arr2)

補(bǔ)充說明:Array的slice和contact方法都不會(huì)修改原數(shù)組,而是會(huì)返回一個(gè)對(duì)原數(shù)組進(jìn)行淺拷貝的新數(shù)組。這兩種方法同Object.assign()一樣,都是對(duì)第一層屬性依次拷貝,如果第一層的屬性是基本數(shù)據(jù)類型,就拷貝值;如果是引用數(shù)據(jù)類型,就拷貝內(nèi)存地址。
三、JS深拷貝
對(duì)對(duì)象的屬性中所有引用類型的值,遍歷到是基本類型的值為止。
3.1、深拷貝實(shí)現(xiàn)方式
(1)JSON.parse(JSON.stringify())
原理:用JSON.stringify()將對(duì)象轉(zhuǎn)成字符串,再用JSON.parse()把字符串解析成對(duì)象。
var obj1 = {
'name' : 'zhangsan',
'language' : [1,[2,3],[4,5]],
};
var obj2 = JSON.parse(JSON.stringify(obj1));
obj2.name = "lisi";
obj2.language[1] = ["二","三"];
console.log('obj1',obj1)
console.log('obj2',obj2)

缺點(diǎn):這種方法可以實(shí)現(xiàn)數(shù)組和對(duì)象和基本數(shù)據(jù)類型的深拷貝,但不能處理函數(shù)。因?yàn)镴SON.stringify()方法是將一個(gè)javascript值轉(zhuǎn)換我一個(gè)JSON字符串,不能接受函數(shù)。其他影響如下:
- 如果對(duì)象中有時(shí)間對(duì)象,那么用該方法拷貝之后的對(duì)象中,時(shí)間是字符串形式而不是時(shí)間對(duì)象
- 如果對(duì)象中有RegExp、Error對(duì)象,那么序列化的結(jié)果是空
- 如果對(duì)象中有函數(shù)或者undefined,那么序列化的結(jié)果會(huì)把函數(shù)或undefined丟失
- 如果對(duì)象中有NAN、infinity、-infinity,那么序列化的結(jié)果會(huì)變成null
- JSON.stringfy()只能序列化對(duì)象的可枚舉自有屬性,如果對(duì)象中有是構(gòu)造函數(shù)生成的,那么拷貝后會(huì)丟棄對(duì)象的constructor
- 如果對(duì)象中存在循環(huán)引用也無法正確實(shí)現(xiàn)深拷貝
(2)手寫深拷貝函數(shù)
通過遞歸實(shí)現(xiàn)深拷貝
function deepCopy(obj){
var result= Array.isArray(obj) ? [] : {}
if (obj && typeof(obj) === 'object') {
for (let i in obj) {
if (obj.hasOwnProperty(i)){ // 思考:這句是否有必要?
if (obj[i] && typeof(obj[i]) === 'object') {
result[i] = deepCopy(obj[i])
} else {
result[i] = obj[i]
}
}
}
}
return result
}
var obj1 = {
a: 1,
b: {
c: 2
}
};
var obj2 = deepCopy(obj1);
obj2.a = '一';
obj2.b.c = '二'
console.log('obj1', obj1)
console.log('obj2', obj2)
obj.hasOwnProperty(prop)用來判斷obj這個(gè)對(duì)象中是否含有prop這個(gè)屬性,返回布爾值,有則true,沒有則false
以上有個(gè)缺陷:當(dāng)遇到兩個(gè)互相引用的對(duì)象時(shí),會(huì)出現(xiàn)死循環(huán)的情況,從而導(dǎo)致爆棧。為了避免相互引用的對(duì)象導(dǎo)致死循環(huán)的情況,則應(yīng)該在遍歷的時(shí)候判斷是否互相引用。
深拷貝函數(shù)改進(jìn)(防止循環(huán)遞歸爆棧)
function deepCopy(obj, parent = null) {
let result = Array.isArray(obj) ? [] : {}
let _parent = parent
// 該字段有父級(jí)則需要追溯該字段的父級(jí)
while(_parent) {
// 如果該字段引用了它的父級(jí),則為循環(huán)引用
if (_parent.originalParent === obj) {
// 循環(huán)引用返回同級(jí)的新對(duì)象
return _parent.currentParent
}
_parent = _parent.parent
}
if (obj && typeof(obj) === 'object') {
for (let i in obj) {
// 如果字段的值也是一個(gè)對(duì)象
if (obj[i] && typeof(obj[i]) === 'object') {
// 遞歸執(zhí)行深拷,將同級(jí)的待拷貝對(duì)象傳遞給parent,方便追溯循環(huán)引用
result[i] = deepCopy(obj[i], {
originalParent: obj,
currentParent: result,
parent: parent
})
} else {
result[i] = obj[i]
}
}
}
return result
}
var obj1 = {
x: 1,
y: 2
};
obj1.z = obj1
var obj2 = deepCopy(obj1)
console.log('obj1', obj1)
console.log('obj2', obj2)
以上代碼可以復(fù)制到瀏覽器去試試吧
深拷貝函數(shù)最終版(支持基本數(shù)據(jù)類型、Array、Object、原型鏈、RegExp、Date類型)
function deepCopy(obj, parent = null) {
let result
let _parent = parent
while(_parent) {
if (_parent.originalParent === obj) {
return _parent.currentParent
}
_parent = _parent.parent
}
if (obj && typeof(obj) === 'object') {
if (obj instanceof RegExp) {
result = new RegExp(obj.source, obj.flags)
} else if (obj instanceof Date) {
result = new Date(obj.getTime())
} else {
if (obj instanceof Array) {
result = []
} else {
let proto = Object.getPrototypeOf(obj)
result = Object.create(proto)
}
for (let i in obj) {
if(obj[i] && typeof(obj[i]) === 'object') {
result[i] = deepCopy(obj[i], {
originalParent: obj,
currentParent: result,
parent: parent
})
} else {
result[i] = obj[i]
}
}
}
} else {
return obj
}
return result
}
var obj1 = {
x: 1
}
//試調(diào)用
function construct(){
this.a = 1,
this.b = {
x:2,
y:3,
z:[4,5,[6]]
},
this.c = [7,8,[9,10]],
this.d = new Date(),
this.e = /abc/ig,
this.f = function(a,b){
return a+b
},
this.g = null,
this.h = undefined,
this.i = "hello",
this.j = Symbol("foo")
}
construct.prototype.str = "I'm prototype"
var obj1 = new construct()
obj1.k = obj1
obj2 = deepCopy(obj1)
obj2.b.x = 999
obj2.c[0] = 666
console.log('obj1', obj1)
console.log('obj2', obj2)
(3)函數(shù)庫
也可以使用一些函數(shù)庫,比如函數(shù)庫lodash,也有提供_.cloneDeep用來做深拷貝;
var _ = require('lodash');
var obj1 = {
a: 1,
b: { f: { g: 1 } },
c: [1, 2, 3]
};
var obj2 = _.cloneDeep(obj1);
console.log(obj1.b.f === obj2.b.f);
// false
參考
http://www.dbjr.com.cn/article/181898.htm
http://www.dbjr.com.cn/article/140928.htm
以上就是詳解JS深拷貝與淺拷貝的詳細(xì)內(nèi)容,更多關(guān)于JS深拷貝與淺拷貝的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
企業(yè)微信掃碼登錄網(wǎng)頁功能實(shí)現(xiàn)代碼
這篇文章主要介紹了企業(yè)微信掃碼登錄網(wǎng)頁功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-01-01
使用OpenLayers3 添加地圖鼠標(biāo)右鍵菜單
這篇文章主要介紹了使用OpenLayers3 添加地圖鼠標(biāo)右鍵菜單的相關(guān)資料,需要的朋友可以參考下2015-12-12
javascript 根據(jù)指定字符把字符串拆分為數(shù)組
javascript 根據(jù)指定字符把字符串拆分為數(shù)組2009-05-05
TypeScript調(diào)整數(shù)組元素順序算法
數(shù)組類型在TS中可以使用多種方式,比較靈活,下面這篇文章主要給大家介紹了關(guān)于TypeScript調(diào)整數(shù)組元素順序算法的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-04-04
微信小程序錯(cuò)誤this.setData報(bào)錯(cuò)及解決過程
這篇文章主要介紹了微信小程序錯(cuò)誤this.setData報(bào)錯(cuò)及解決過程,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09

