什么是 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");
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3