1. Recursive implementation
Recursive implementation is the most basic deep copy method. It traverses object properties, and if the property itself is a reference type, it continues to recursively copy.
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;
const clone = Array.isArray(obj) ? [] : {};
for (let key in obj) {
clone[key] = deepClone(obj[key]);
}
return clone;
}
2. JSON implementation
JSON.parse and JSON.stringify provide deep copy functions, but only for data types that support serialization and deserialization, such as basic data types and some object types.
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
3. Object.assign implementation
Object.assign can also implement deep copy, but only enumerable properties can be copied, and inherited properties cannot be copied.
function deepClone(obj) {
return Object.assign({}, obj);
}
4. lodash implementation
lodash is a popular JavaScript tool library that provides the _.cloneDeep method for deep copying
const _ = require('lodash');
function deepClone(obj) {
return _.cloneDeep(obj);
}