什麼是 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中文網其他相關文章!