What is structuredClone()?
Why is it a game-changer?
const original = { name: "Alice", details: { age: 25 } }; const shallowCopy = { ...original }; shallowCopy.details.age = 30; console.log(original.details.age); // 30 console.log(shallowCopy.details.age); // 30
What's happening?
const original = { name: "Alice", details: { age: 25 } }; const deepCopy = JSON.parse(JSON.stringify(original)); deepCopy.details.age = 30; console.log(original.details.age); // 25 console.log(deepCopy.details.age); // 30
What's happening?
const original = { name: "Alice", details: { age: 25 } }; const clone = structuredClone(original); clone.details.age = 30; console.log(original.details.age); // 25 console.log(clone.details.age); // 30
const original = { name: "Alice" }; original.self = original; // This will cause an error: const shallowCopy = { ...original }; // TypeError: Converting circular structure to JSON
What's happening?
const original = { name: "Alice" }; original.self = original; // This will cause an error: const jsonCopy = JSON.parse(JSON.stringify(original)); // TypeError: Converting circular structure to JSON
What's happening?
const original = { name: "Alice" }; original.self = original; const clone = structuredClone(original); console.log(clone !== original); // true console.log(clone.self === clone); // true
const original = { name: "Alice", greet: () => "Hello!", value: undefined }; const shallowCopy = { ...original }; console.log(shallowCopy.greet()); // "Hello!" console.log(shallowCopy.value); // undefined
What's happening?
const original = { name: "Alice", greet: () => "Hello!", value: undefined }; const jsonCopy = JSON.parse(JSON.stringify(original)); console.log(jsonCopy.greet); // undefined console.log(jsonCopy.value); // undefined
What's happening?
const original = { name: "Alice", greet: () => "Hello!", value: undefined }; const clone = structuredClone(original); console.log(clone.greet); // undefined console.log(clone.value); // undefined
const largeArray = new Array(1e6).fill({ key: "value" }); console.time("structuredClone"); const clone = structuredClone(largeArray); console.timeEnd("structuredClone"); console.time("JSON.stringify JSON.parse"); const jsonCopy = JSON.parse(JSON.stringify(largeArray)); console.timeEnd("JSON.stringify JSON.parse");
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3