StructuredClone():JavaScript中深拷貝對(duì)象的最簡單方法

深拷貝是傳遞或存儲(chǔ)數(shù)據(jù)時(shí)的一項(xiàng)常規(guī)編程任務(wù)。
- 淺拷貝:只復(fù)制對(duì)象的第一層
 - 深拷貝:復(fù)制對(duì)象的所有層級(jí)
 
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但一直以來,我們都沒有一種內(nèi)置的方法來完美地深度復(fù)制對(duì)象,這一直是一個(gè)痛點(diǎn)。
我們總是不得不依賴第三方庫來進(jìn)行深度復(fù)制并保留循環(huán)引用。
現(xiàn)在,這一切都因新的structuredClone()而改變了——它是一種簡單高效的方法,可以深度復(fù)制任何對(duì)象。
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這是你永遠(yuǎn)無法用JSON stringify/parse技巧實(shí)現(xiàn)的:

想深入多少層都可以:
// ??
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你應(yīng)該知道的限制
structuredClone()非常強(qiáng)大,但它有一些你應(yīng)該了解的重要弱點(diǎn):
無法克隆函數(shù)或方法

這是因?yàn)樗褂玫奶厥馑惴ā?/p>

無法克隆DOM元素
<input id="text-field" />const input = document.getElementById('text-field');
const inputClone = structuredClone(input);
console.log(inputClone);
不保留RegExp的lastIndex屬性
我是說,沒人會(huì)去克隆正則表達(dá)式,但這是值得注意的一點(diǎn):
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其他限制
了解這些限制很重要,以避免使用該函數(shù)時(shí)出現(xiàn)意外行為。
部分克隆,部分移動(dòng)
這是一個(gè)更復(fù)雜的情況。
你將內(nèi)部對(duì)象從源對(duì)象轉(zhuǎn)移到克隆對(duì)象,而不是復(fù)制。
這意味著源對(duì)象中沒有留下任何可以改變的東西:
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ā)者工具箱中的一個(gè)寶貴補(bǔ)充,使對(duì)象克隆比以往任何時(shí)候都更容易。















 
 
 










 
 
 
 