帮我写一个js深拷贝的代码
时间: 2023-07-19 20:35:17 浏览: 80
好的,以下是一个简单的 JS 深拷贝的代码实现:
```javascript
function deepCopy(obj) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
let copy = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
copy[key] = deepCopy(obj[key]);
}
}
return copy;
}
```
使用方法:
```javascript
let original = {
name: 'John',
age: 30,
hobbies: ['reading', 'traveling'],
address: {
city: 'New York',
state: 'NY'
}
};
let copy = deepCopy(original);
console.log(copy); // { name: 'John', age: 30, hobbies: [ 'reading', 'traveling' ], address: { city: 'New York', state: 'NY' } }
// 修改副本的值
copy.name = 'Mike';
copy.hobbies.push('swimming');
copy.address.city = 'Los Angeles';
// 验证原始对象是否被修改
console.log(original); // { name: 'John', age: 30, hobbies: [ 'reading', 'traveling' ], address: { city: 'New York', state: 'NY' } }
```
阅读全文