<script>
const obj ={
name: '小明',
age: 18,
hobby: ['吃饭','睡觉'],
info :{
address: '北京',
area: '朝阳',
},
show() {
console.log(123)
}
}
const str = JSON.stringify(obj)
const result = JSON.parse(str)
</script>
注意:这种方法不会深拷贝原来对象中的函数 ,函数会丢失
<script>
const obj = {
name: 'zs',
age: 20,
hobby: ['吃饭', '睡觉', '打豆豆'],
info: {
address: '北京',
area: '顺义',
class: [1, 2, 3]
},
show() {
console.log('show函数被调用了!')
}
}
function deepClone(val) {
if (typeof val === 'object' && val !== null) {
// 有必要进行深拷贝
// newObj 中存放的,是深拷贝的结果
const newObj = Array.isArray(val) ? [] : {}
// TODO:对 val 进行 for...in... 深拷贝
for (const k in val) {
// console.log(k, val[k])
newObj[k] = deepClone(val[k])
}
return newObj
} else {
// 没必要进行深拷贝
return val
}
}
// const result = deepClone(['a', 'b', 'c'])
// const result = deepClone({ name: 'zs', age: 20, info: { a: 1, b: 2 } })
const result = deepClone(obj)
console.log(result)
</script>
递归方式实现深拷贝