JSONparseJSONstringify
JSON.parse(JSON.stringify()) is a technique used to create a deep clone of an object in JavaScript.
JSON.stringify() converts a JavaScript object into a JSON string, while JSON.parse() converts a JSON string back into a JavaScript object. By combining these two methods, we can create a new object that is an exact copy of the original.
Here's an example:
const originalObject = { a: 1, b: { c: 2 } };
const clonedObject = JSON.parse(JSON.stringify(originalObject));
console.log(originalObject); // { a: 1, b: { c: 2 } }
console.log(clonedObject); // { a: 1, b: { c: 2 } }
clonedObject.b.c = 3;
console.log(originalObject); // { a: 1, b: { c: 2 } }
console.log(clonedObject); // { a: 1, b: { c: 3 } }
In this example, we create an object called originalObject with a nested object inside it. We then use JSON.stringify() to convert originalObject into a JSON string, and then JSON.parse() to convert the JSON string back into a JavaScript object. This creates a new object called clonedObject that is a copy of originalObject.
We can then modify clonedObject without affecting the original object, as seen in the last two console.log statements
原文地址: https://www.cveoy.top/t/topic/hdFU 著作权归作者所有。请勿转载和采集!