在Javascript中制作对象的深层副本可以通过以下几种方式实现:
const obj = { name: 'John', age: 30, address: { city: 'New York', country: 'USA' } };
const clone = { ...obj };
const obj = { name: 'John', age: 30, address: { city: 'New York', country: 'USA' } };
const clone = JSON.parse(JSON.stringify(obj));
function deepClone(obj) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
const clone = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
clone[key] = deepClone(obj[key]);
}
}
return clone;
}
const obj = { name: 'John', age: 30, address: { city: 'New York', country: 'USA' } };
const clone = deepClone(obj);
以上是在Javascript中制作对象的深层副本的几种常用方式。根据具体的场景和需求,选择合适的方式进行对象复制。
领取专属 10元无门槛券
手把手带您无忧上云