structuredClone() 全域性函式
注意:此功能在Web Workers 中可用。
全域性structuredClone()方法使用結構化克隆演算法建立給定值的深複製。
該方法還允許將原始值中的可傳輸物件傳輸到新物件,而不是克隆到新物件。傳輸的物件與原始物件分離並附加到新物件;它們在原始物件中不再可訪問。
語法
js
structuredClone(value)
structuredClone(value, options)
引數
返回值
返回值是原始value的深複製。
異常
DataCloneErrorDOMException-
如果輸入值的任何部分不可序列化,則丟擲此異常。
描述
此函式可用於深複製 JavaScript 值。它還支援迴圈引用,如下所示
js
// Create an object with a value and a circular reference to itself.
const original = { name: "MDN" };
original.itself = original;
// Clone it
const clone = structuredClone(original);
console.assert(clone !== original); // the objects are not the same (not same identity)
console.assert(clone.name === "MDN"); // they do have the same values
console.assert(clone.itself === clone); // and the circular reference is preserved
傳輸值
可以使用options引數的transfer屬性,將可傳輸物件(僅)傳輸到克隆的物件,而不是複製到克隆的物件。傳輸會使原始物件無法使用。
注意:在非同步驗證緩衝區中的一些資料然後再儲存它時,這可能很有用。為了避免在儲存資料之前修改緩衝區,您可以克隆緩衝區並驗證該資料。如果您還傳輸資料,則任何嘗試修改原始緩衝區的操作都將失敗,從而防止意外誤用。
以下程式碼演示瞭如何克隆陣列並將它的底層資源傳輸到新物件。返回後,原始uInt8Array.buffer將被清除。
js
// 16MB = 1024 * 1024 * 16
const uInt8Array = Uint8Array.from({ length: 1024 * 1024 * 16 }, (v, i) => i);
const transferred = structuredClone(uInt8Array, {
transfer: [uInt8Array.buffer],
});
console.log(uInt8Array.byteLength); // 0
您可以克隆任意數量的物件並傳輸這些物件的任意子集。例如,下面的程式碼將從傳入的值中傳輸arrayBuffer1,但不傳輸arrayBuffer2。
js
const transferred = structuredClone(
{ x: { y: { z: arrayBuffer1, w: arrayBuffer2 } } },
{ transfer: [arrayBuffer1] },
);
示例
克隆物件
在此示例中,我們克隆一個包含一個成員(一個數組)的物件。克隆後,對每個物件所做的更改不會影響另一個物件。
js
const mushrooms1 = {
amanita: ["muscaria", "virosa"],
};
const mushrooms2 = structuredClone(mushrooms1);
mushrooms2.amanita.push("pantherina");
mushrooms1.amanita.pop();
console.log(mushrooms2.amanita); // ["muscaria", "virosa", "pantherina"]
console.log(mushrooms1.amanita); // ["muscaria"]
傳輸物件
在此示例中,我們建立一個ArrayBuffer,然後克隆它所屬的物件,並傳輸該緩衝區。我們可以在克隆的物件中使用該緩衝區,但是如果我們嘗試使用原始緩衝區,我們將獲得異常。
js
// Create an ArrayBuffer with a size in bytes
const buffer1 = new ArrayBuffer(16);
const object1 = {
buffer: buffer1,
};
// Clone the object containing the buffer, and transfer it
const object2 = structuredClone(object1, { transfer: [buffer1] });
// Create an array from the cloned buffer
const int32View2 = new Int32Array(object2.buffer);
int32View2[0] = 42;
console.log(int32View2[0]);
// Creating an array from the original buffer throws a TypeError
const int32View1 = new Int32Array(object1.buffer);
規範
| 規範 |
|---|
| HTML 標準 # dom-structuredclone |
瀏覽器相容性
BCD 表僅在啟用 JavaScript 的瀏覽器中載入。