JS實現(xiàn)深拷貝和淺拷貝的方式詳解
說道數(shù)據(jù)拷貝就離不開數(shù)據(jù)類型,在JS中數(shù)據(jù)類型分為基本類型和引用類型 基本類型:
number, boolean,string,symbol,bigint,undefined,null
引用類型:
object 以及一些標(biāo)準(zhǔn)內(nèi)置對象 Array、RegExp、String、Map、Set..
一. 基本類型數(shù)據(jù)拷貝
基本類型數(shù)據(jù)都是值類型,存儲在棧內(nèi)存中,每次賦值都是一次復(fù)制的過程
var a = 12; var b = a;
二. 引用類型數(shù)據(jù)拷貝
1、淺拷貝
只拷貝對象的一層數(shù)據(jù),再深處層次的引用類型value將只會拷貝引用 實現(xiàn)方式:
1.Object.assign() 和 ES6的拓展運算符
通常我們用 Object.assign() 方法來實現(xiàn)淺拷貝。 Object.assign()用于將所有可枚舉屬性的值從一個或多個源對象分配到目標(biāo)對象。它將返回目標(biāo)對象。
let aa = {
a: undefined,
func: function(){console.log(1)},
b:2,
c: {x: 'xxx', xx: undefined},
d: null,
e: BigInt(100),
f: Symbol('s')
}
let bb = Object.assign({}, aa) // 或者 let bb = {...aa}
aa.c.x = 111
console.log(bb)
// 第一層拷貝,遇到引用類型的值就會只拷貝引用
// {
// a: undefined,
// func: [Function: func],
// b: 2,
// c: { x: 111, xx: undefined },
// d: null,
// e: 100n,
// f: Symbol(s)
// }2.Object.create
Object.create()方法創(chuàng)建一個新對象,使用現(xiàn)有的對象來提供新創(chuàng)建的對象的__proto__。Object.create(proto,[propertiesObject])接收兩個參數(shù)一個是新創(chuàng)建對象的__proto__, 一個屬性列表
let aa = {
a: undefined,
func: function(){console.log(1)},
b:2,
c: {x: 'xxx', xx: undefined},
}
let bb = Object.create(aa, Object.getOwnPropertyDescriptors(aa))
aa.c.x = 111
console.log(bb)
// 第一層拷貝,遇到引用類型的值就會只拷貝引用
// {
// a: undefined,
// func: [Function: func],
// b: 2,
// c: { x: 111, xx: undefined },
// }2、深拷貝
在拷貝一個對象的時候為了避免修改對數(shù)據(jù)造成的影響,必須使用深拷貝。
實現(xiàn)方式:
1、 通過JSON.stringify()
var a = {a:1, b: 2}
var b = JSON.stringify(a);
a.a = 'a'
console.log(a, b) // { a: 'a', b: 2 } {"a":1,"b":2}JSON.stringify()進(jìn)行深拷貝有弊端: 忽略value為function, undefind, symbol, 并且在序列化BigInt時會拋出語法錯誤:TypeError: Do not know how to serialize a BigInt
// 序列化function, undefind, symbol,忽略--------------------------------------------------------
var obj = {
a:function(){},
b: undefined,
c: null,
d: Symbol('s'),
}
var objCopyed = JSON.stringify(obj);
console.log("a:", a)
// obj: { a: [Function: a], b: undefined, c: null, d: Symbol(s) }
console.log("objCopyed:", objCopyed)
// objCopyed: {"c":null}
// 序列化bigint拋出錯誤--------------------------------------------------------
var obj = {
a: 1,
e: BigInt(9007199254740991)
}
var objCopyed = JSON.stringify(obj); // TypeError: Do not know how to serialize a BigInt2、遞歸實現(xiàn)
const deepCopy = (obj) => {
// 優(yōu)化 把值類型復(fù)制方放到這里可以少一次deepCopy調(diào)用
// if(!obj || typeof obj !== 'object') throw new Error("請傳入非空對象")
if(!obj || typeof obj !== 'object') return obj
let result = {}
if (Object.prototype.toString.call(obj).indexOf('Array') > 0) {
result = []
}
// 另一種循環(huán)方式
// for (let key in obj) {
// if (obj.hasOwnProperty(key)) {
// result[key] = deepClone(obj[key])
// }
// }
Object.keys(obj).forEach(key => {
// 優(yōu)化 把值類型復(fù)制方放到這里可以少一次deepCopy調(diào)用
// if (obj[key] && typeof obj[key] === 'object') {
// result[key] = deepCopy(obj[key])
// }else{
// result[key] = obj[key]
// }
result[key] = deepCopy(obj[key])
});
return result
}
let aa = {
a: undefined,
func: function(){console.log(1)},
b:2,
c: {x: 'xxx', xx: undefined},
d: null,
e: BigInt(100),
f: Symbol('s')
}
let bb = deepCopy(aa)
aa.c.x = 123
aa.func = {}
console.log("aa", aa)
console.log("bb", bb)
// aa {
// a: undefined,
// func: {},
// b: 2,
// c: { x: 123, xx: undefined },
// d: null,
// e: 100n,
// f: Symbol(s)
// }
// bb {
// a: undefined,
// func: [Function: func],
// b: 2,
// c: { x: 'xxx', xx: undefined },
// d: null,
// e: 100n,
// f: Symbol(s)
// }手寫深拷貝等這些工具方法,在實際生產(chǎn)中99.99%不會用到,畢竟有l(wèi)odash、underscore這些方便的工具庫呢
到此這篇關(guān)于JS實現(xiàn)深拷貝和淺拷貝的方式詳解的文章就介紹到這了,更多相關(guān)JS深拷貝 淺拷貝內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解微信圖片防盜鏈“此圖片來自微信公眾平臺 未經(jīng)允許不得引用”的解決方案
這篇文章主要介紹了詳解微信圖片防盜鏈“此圖片來自微信公眾平臺 未經(jīng)允許不得引用”的解決方案,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-04-04
微信小程序在其他頁面監(jiān)聽globalData中值的變化
這篇文章主要給大家介紹了關(guān)于微信小程序如何在其他頁面監(jiān)聽globalData中值的變化的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用微信小程序具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
微信分享的標(biāo)題、縮略圖、連接及描述設(shè)置方法
微信分享的標(biāo)題、縮略圖、連接及描述該如何設(shè)置,這個問題確實難道不少朋友,下面有個示例,大家可以看看2014-10-10
關(guān)于微信小程序獲取小程序碼并接受buffer流保存為圖片的方法
這篇文章主要介紹了關(guān)于微信小程序獲取小程序碼并接受buffer流保存為圖片的方法,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用小程序具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧<BR>2019-06-06
JS使用可選鏈操作符 (?.) 進(jìn)行空值檢查的操作
在 JavaScript 中,處理嵌套對象或數(shù)組時,經(jīng)常會遇到空值檢查的問題,傳統(tǒng)的空值檢查通常比較繁瑣,容易導(dǎo)致代碼冗長且難以閱讀,ES2020 引入了可選鏈操作符 (?.),極大地簡化了這些檢查過程,本文介紹了JS使用可選鏈操作符 (?.) 進(jìn)行空值檢查的操作2024-12-12

