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");
The above is the detailed content of Bye-Bye `JSON.stringify()` and `{...obj}`, Hello `structuredClone()`!. For more information, please follow other related articles on the PHP Chinese website!