StructuredClone():JavaScript中深拷貝對象的最簡單方法
深拷貝是傳遞或存儲數據時的一項常規(guī)編程任務。
- 淺拷貝:只復制對象的第一層
- 深拷貝:復制對象的所有層級
const obj = { name: 'Tari', friends: [{ name: 'Messi' }] };
const shallowCopy = { ...obj };
const deepCopy = dCopy(obj);
console.log(obj.friends === shallowCopy.friends); // ? true
console.log(obj.friends === deepCopy.friends); // ? false
但一直以來,我們都沒有一種內置的方法來完美地深度復制對象,這一直是一個痛點。
我們總是不得不依賴第三方庫來進行深度復制并保留循環(huán)引用。
現在,這一切都因新的structuredClone()而改變了——它是一種簡單高效的方法,可以深度復制任何對象。
const obj = { name: 'Tari', friends: [{ name: 'Messi' }] };
const clonedObj = structuredClone(obj);
console.log(obj.name === clonedObj); // false
console.log(obj.friends === clonedObj.friends); // false
輕松克隆循環(huán)引用:
const car = {
make: 'Toyota',
};
// ?? 循環(huán)引用
car.basedOn = car;
const cloned = structuredClone(car);
console.log(car.basedOn === cloned.basedOn); // false
// ?? 循環(huán)引用被克隆
console.log(car === car.basedOn); // true
這是你永遠無法用JSON stringify/parse技巧實現的:
想深入多少層都可以:
// ??
const obj = {
a: {
b: {
c: {
d: {
e: 'Coding Beauty',
},
},
},
},
};
const clone = structuredClone(obj);
console.log(clone.a.b.c.d === obj.a.b.c.d); // false
console.log(clone.a.b.c.d.e); // Coding Beauty
你應該知道的限制
structuredClone()非常強大,但它有一些你應該了解的重要弱點:
無法克隆函數或方法
這是因為它使用的特殊算法。
無法克隆DOM元素
<input id="text-field" />
const input = document.getElementById('text-field');
const inputClone = structuredClone(input);
console.log(inputClone);
不保留RegExp的lastIndex屬性
我是說,沒人會去克隆正則表達式,但這是值得注意的一點:
const regex = /beauty/g;
const str = 'Coding Beauty: JS problems are solved at Coding Beauty';
console.log(regex.index);
console.log(regex.lastIndex); // 7
const regexClone = structuredClone(regex);
console.log(regexClone.lastIndex); // 0
其他限制
了解這些限制很重要,以避免使用該函數時出現意外行為。
部分克隆,部分移動
這是一個更復雜的情況。
你將內部對象從源對象轉移到克隆對象,而不是復制。
這意味著源對象中沒有留下任何可以改變的東西:
const uInt8Array = Uint8Array.from(
{ length: 1024 * 1024 * 16 },
(v, i) => i
);
const transferred = structuredClone(uInt8Array, {
transfer: [uInt8Array.buffer],
});
console.log(uInt8Array.byteLength); // 0
總的來說,structuredClone()是JavaScript開發(fā)者工具箱中的一個寶貴補充,使對象克隆比以往任何時候都更容易。