什么是 StructuredClone()?
为什么它会改变游戏规则?
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
发生什么事了?
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
发生什么事了?
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
发生什么事了?
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
发生了什么事?
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
发生了什么事?
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
发生了什么事?
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");
以上是再见`JSON.stringify()`和`{...obj}`,你好`structedClone()`!的详细内容。更多信息请关注PHP中文网其他相关文章!