一起聊聊 JavaScript 中的 structuredClone 現(xiàn)代深拷貝
在JavaScript中,實(shí)現(xiàn)深拷貝的方式有很多種,每種方式都有其優(yōu)點(diǎn)和缺點(diǎn)。今天介紹一種原生JavaScript提供的structuredClone實(shí)現(xiàn)深拷貝。
下面列舉一些常見(jiàn)的方式,以及它們的代碼示例和優(yōu)缺點(diǎn):
1. 使用JSON.parse(JSON.stringify(obj))
代碼示例:
function deepClone(obj) {
    return JSON.parse(JSON.stringify(obj));
}優(yōu)點(diǎn):簡(jiǎn)單易行,對(duì)于大多數(shù)對(duì)象類型有效。
缺點(diǎn):不能復(fù)制原型鏈,對(duì)于包含循環(huán)引用的對(duì)象可能出現(xiàn)問(wèn)題。比如以下代碼:
const calendarEvent = {
  date: new Date()
}
const problematicCopy = JSON.parse(JSON.stringify(calendarEvent))最終得到的date不是Data對(duì)象,而是字符串。
{
    "date": "2024-03-02T03:43:35.890Z"
}這是因?yàn)镴SON.stringify只能處理基本的對(duì)象、數(shù)組。任何其他類型都沒(méi)有按預(yù)期處理。例如,日期轉(zhuǎn)換為字符串。Set/Map只是轉(zhuǎn)換為{}。
const kitchenSink = {
  set: new Set([1, 3, 3]),
  map: new Map([[1, 2]]),
  regex: /foo/,
  deep: { array: [ new File(someBlobData, 'file.txt') ] },
  error: new Error('Hello!')
}
const veryProblematicCopy = JSON.parse(JSON.stringify(kitchenSink))最終得到如下數(shù)據(jù):
{
  "set": {},
  "map": {},
  "regex": {},
  "deep": {
    "array": [
      {}
    ]
  },
  "error": {},
}2. 使用遞歸
代碼示例:
function deepClone(obj) {
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }
    let clone = obj.constructor();
    for (let attr in obj) {
        if (obj.hasOwnProperty(attr)) {
            clone[attr] = this.deepClone(obj[attr]);
        }
    }
    return clone;
}優(yōu)點(diǎn):對(duì)于任何類型的對(duì)象都有效,包括循環(huán)引用。
缺點(diǎn):對(duì)于大型對(duì)象可能會(huì)消耗大量?jī)?nèi)存,并可能導(dǎo)致堆棧溢出。
3. 第三方庫(kù),如 lodash 的 _.cloneDeep 方法
代碼示例:
const _ = require('lodash');
function deepClone(obj) {
    return _.cloneDeep(obj);
}優(yōu)點(diǎn):支持更多類型的對(duì)象和庫(kù),例如,支持 Proxy 對(duì)象。
缺點(diǎn):會(huì)引入依賴導(dǎo)致項(xiàng)目體積增大。
圖片
因?yàn)檫@個(gè)函數(shù)會(huì)導(dǎo)致17.4kb的依賴引入,如果只是引入lodash會(huì)更高。
4. 現(xiàn)代深拷貝structuredClone
在現(xiàn)代瀏覽器中,可以使用 structuredClone 方法來(lái)實(shí)現(xiàn)深拷貝,它是一種更高效、更安全的深拷貝方式。
以下是一個(gè)示例代碼,演示如何使用 structuredClone 進(jìn)行深拷貝:
const kitchenSink = {
  set: new Set([1, 3, 3]),
  map: new Map([[1, 2]]),
  regex: /foo/,
  deep: { array: [ new File(someBlobData, 'file.txt') ] },
  error: new Error('Hello!')
}
kitchenSink.circular = kitchenSink
const clonedSink = structuredClone(kitchenSink)structuredClone可以做到:
- 拷貝無(wú)限嵌套的對(duì)象和數(shù)組
 - 拷貝循環(huán)引用
 - 拷貝各種各樣的JavaScript類型,如Date、Set、Map、Error、RegExp、ArrayBuffer、Blob、File、ImageData等
 
哪些不能拷貝:
- 函數(shù)
 - DOM節(jié)點(diǎn)
 - 屬性描述、setter和getter
 - 對(duì)象原型鏈
 
所支持的完整列表:
Array、ArrayBuffer、Boolean、DataView、Date、Error類型(下面具體列出的類型)、Map、Object,但僅限于普通對(duì)象、原始類型,除了symbol(又名number、string、null、undefined、boolean、BigInt)、RegExp、Set、TypedArray
Error類型:
Error, EvalError, RangeError, ReferenceError , SyntaxError, TypeError, URIError
Web/API類型:
AudioData, Blob, CryptoKey, DOMException, DOMMatrix, DOMMatrixReadOnly, DOMPoint, DomQuad, DomRect, File, FileList, FileSystemDirectoryHandle, FileSystemFileHandle, FileSystemHandle, ImageBitmap, ImageData, RTCCertificate, VideoFrame
值得慶幸的是 structuredClone 在所有主流瀏覽器中都受支持,也支持Node.js和Deno。
圖片
最后
我們現(xiàn)在終于可以直接使用原生JavaScript中的structuredClone能力實(shí)現(xiàn)深度拷貝對(duì)象。每種方式都有其優(yōu)缺點(diǎn),具體使用方式取決于你的需求和目標(biāo)對(duì)象的類型。
參考
- Deep Cloning Objects in JavaScript, the Modern Way(www.builder.io/blog/structured-clone)
 - mozilla structuredClone(developer.mozilla.org/zh-CN/docs/Web/API/structuredClone)
 















 
 
 
















 
 
 
 