JavaScript深拷貝的幾種實(shí)現(xiàn)方法實(shí)例
淺拷貝與深拷貝
淺拷貝是創(chuàng)建一個(gè)新對(duì)象,這個(gè)對(duì)象有著原始對(duì)象屬性值的拷貝。如果屬性是基本類(lèi)型,拷貝的就是基本類(lèi)型的值,如果屬性是引用類(lèi)型,拷貝的是內(nèi)存地址 。如果不進(jìn)行深拷貝,其中一個(gè)對(duì)象改變了對(duì)象的值,就會(huì)影響到另一個(gè)對(duì)象的值。
深拷貝是將一個(gè)對(duì)象從內(nèi)存中完整的拷貝一份出來(lái),從堆內(nèi)存中開(kāi)辟一個(gè)新的區(qū)域存放新對(duì)象,且修改新對(duì)象不會(huì)影響原對(duì)象。
1.JSON.parse(JSON.stringify(obj))
一般情況下對(duì)普通對(duì)象需要進(jìn)行深拷貝,可以使用這種方法進(jìn)行深拷貝操作,這種是最簡(jiǎn)單且代碼量最少的深拷貝方法。
let a = {a:1,b:2}
let b = JSON.parse(JSON.stringify(a))
a.a = 11
console.log(a)//{a:1,b:2}
console.log(b)//{a:11,b:2}1.1 JSON.parse(JSON.stringify(obj))深淺拷貝的缺陷
let a = {
name: 'Jack',
age: 18,
hobbit: ['sing', {type: 'sports', value: 'run'}],
score: {
math: 'A',
},
run: function() {},
walk: undefined,
fly: NaN,
cy: null,
date: new Date()
}
let b = JSON.parse(JSON.stringify(a))
console.log(b)
// {
// age: 18,
// cy: null,
// date: "2022-05-15T08:04:06.808Z"
// fly: null,
// hobbit: (3) ["dance", "sing", {…}],
// name: "Jack",
// score: {math: "A"},
// }取不到值為 undefined 的 key;如果對(duì)象里有函數(shù),函數(shù)無(wú)法被拷貝下來(lái);無(wú)法拷貝copyObj對(duì)象原型鏈上的屬性和方法;對(duì)象轉(zhuǎn)變?yōu)?date 字符串。
2.普通遞歸函數(shù)實(shí)現(xiàn)深拷貝
function deepClone(source) {
if (typeof source !== 'object' || source == null) {
return source;
}
const target = Array.isArray(source) ? [] : {};
for (const key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
if (typeof source[key] === 'object' && source[key] !== null) {
target[key] = deepClone(source[key]);
} else {
target[key] = source[key];
}
}
}
return target;
}2.1解決循環(huán)引用和symblo類(lèi)型
function cloneDeep(source, hash = new WeakMap()) {
if (typeof source !== 'object' || source === null) {
return source;
}
if (hash.has(source)) {
return hash.get(source);
}
const target = Array.isArray(source) ? [] : {};
Reflect.ownKeys(source).forEach(key => {
const val = source[key];
if (typeof val === 'object' && val != null) {
target[key] = cloneDeep(val, hash);
} else {
target[key] = val;
}
})
return target;
}3.兼容多種數(shù)據(jù)類(lèi)型
const deepClone = (source, cache) => {
if(!cache){
cache = new Map()
}
if(source instanceof Object) { // 不考慮跨 iframe
if(cache.get(source)) { return cache.get(source) }
let result
if(source instanceof Function) {
if(source.prototype) { // 有 prototype 就是普通函數(shù)
result = function(){ return source.apply(this, arguments) }
} else {
result = (...args) => { return source.call(undefined, ...args) }
}
} else if(source instanceof Array) {
result = []
} else if(source instanceof Date) {
result = new Date(source - 0)
} else if(source instanceof RegExp) {
result = new RegExp(source.source, source.flags)
} else {
result = {}
}
cache.set(source, result)
for(let key in source) {
if(source.hasOwnProperty(key)){
result[key] = deepClone(source[key], cache)
}
}
return result
} else {
return source
}
}4.jQuery.extend()方法
可以使用$.extend進(jìn)行深拷貝
$.extend(deepCopy, target, object1, [objectN])//第一個(gè)參數(shù)為true,就是深拷貝
let a = {
a: 1,
b: { d:8},
c: [1, 2, 3]
};
let b = $.extend(true, {}, a);
console.log(a.b.d === b.b.d); // false4.1 jQuery.extend 源碼
jQuery.extend = jQuery.fn.extend = function() {
var options,
name,
src,
copy,
copyIsArray,
clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if (typeof target === "boolean") {
deep = target;
// Skip the boolean and the target
target = arguments[i] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== "object" && !jQuery.isFunction(target)) {
target = {};
}總結(jié)
到此這篇關(guān)于JavaScript深拷貝的文章就介紹到這了,更多相關(guān)js深拷貝內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java、javascript實(shí)現(xiàn)附件下載示例
在web開(kāi)發(fā)中,經(jīng)常需要開(kāi)發(fā)“下載”這一模塊,下面使用java、javascript實(shí)現(xiàn)附件下載,需要的朋友可以參考下2014-08-08
一分鐘學(xué)會(huì)JavaScript中的try-catch
這篇文章主要給大家介紹了關(guān)于如何通過(guò)一分鐘學(xué)會(huì)JavaScript中try-catch的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
使用next.js開(kāi)發(fā)網(wǎng)址縮短服務(wù)的方法
這篇文章主要介紹了使用next.js開(kāi)發(fā)網(wǎng)址縮短服務(wù),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06
input框中自動(dòng)展示當(dāng)前日期yyyy/mm/dd的實(shí)現(xiàn)方法
下面小編就為大家?guī)?lái)一篇input框中自動(dòng)展示當(dāng)前日期yyyy/mm/dd的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-07-07
基于JavaScript實(shí)現(xiàn)根據(jù)手機(jī)定位獲取當(dāng)前具體位置(X省X市X縣X街道X號(hào))
這篇文章主要介紹了基于JavaScript實(shí)現(xiàn)根據(jù)手機(jī)定位獲取當(dāng)前具體位置(X省X市X縣X街道X號(hào))的相關(guān)資料,需要的朋友可以參考下2015-12-12

