1. 浅拷贝
首先浅拷贝和深拷贝只针对引用类型
浅拷贝:拷贝的是地址
常见方法:
1. 拷贝对象:Object.assgin() / 展开运算符 {...obj} 拷贝对象
2.拷贝数组:Array.prototype.concat() 或者 [...arr]
const obj = { uname: 'allen', age: 18 } const o = { ...obj } console.log(o) // {uname: 'allen', age: 18} o.uname = 'kunkun' console.log(o) // {uname: 'kunkun', age: 18} console.log(obj)// {uname: 'allen', age: 18}
const obj = { uname: 'allen', age: 18 } const o = {} Object.assign(o, obj) console.log(o) // {uname: 'allen', age: 18} o.uname = 'kunkun' console.log(o) // {uname: 'kunkun', age: 18} console.log(obj)// {uname: 'allen', age: 18}
如果是简单数据类型拷贝值,引用数据类型拷贝的是地址 (简单理解: 如果是单层对象,没问题,如果有多层就有问题)
const obj = { uname: 'allen', age: 18, family: { mother: '妈妈' } } const o = {} Object.assign(o, obj) console.log(o) o.uname = 'kunkun' // 修改对象里面的family还是会有影响 o.family.mother = '你的妈妈' console.log(o) console.log(obj)
2. 深拷贝
首先浅拷贝和深拷贝只针对引用类型
深拷贝:拷贝的是对象,不是地址
常见方法:
1. 通过递归实现深拷贝
2. lodash/cloneDeep
3. 通过JSON.stringify()实现
函数递归:
如果一个函数在内部可以调用其本身,那么这个函数就是递归函数
let i = 1 // fn 就是递归函数 function fn() { console.log(i) if (i >= 6) { return } i++ fn() // 函数内部调用函数自己 } fn()
简单理解:函数内部自己调用自己, 这个函数就是递归函数
递归函数的作用和循环效果类似
由于递归很容易发生“栈溢出”错误(stack overflow),所以必须要加退出条件 return
常见方法:
1. 通过递归实现深拷贝
const obj = { uname: 'allen', age: 18, like: ['唱', '跳', '篮球'], family: { mother: '妈妈' } } const o = {} function deepCopy(newObj, oldObj) { for (let k in oldObj) { if (oldObj[k] instanceof Array) { newObj[k] = [] deepCopy(newObj[k], oldObj[k]) } else if (oldObj[k] instanceof Object) { newObj[k] = {} deepCopy(newObj[k], oldObj[k]) } else { newObj[k] = oldObj[k] } } } deepCopy(o, obj) o.like[0] = 'kunkun' o.family.mother = 'mama' console.log(obj) console.log(o)
2. js库lodash里面cloneDeep内部实现了深拷贝
<script src="./js/lodash.min.js"></script> <script> const obj = { uname: 'allen', age: 18, like: ['唱', '跳', '篮球'], family: { mother: '妈妈' } } // 语法:_.cloneDeep(要被克隆的对象) const o = _.cloneDeep(obj) o.like[0] = 'kunkun222' o.family.mother = 'mama222' console.log(obj) console.log(o) </script>
3. 通过JSON.stringify()实现
const obj = { uname: 'allen', age: 18, like: ['唱', '跳', '篮球'], family: { mother: '妈妈' } } const o = JSON.parse(JSON.stringify(obj)) o.like[0] = 'kunkun333' o.family.mother = 'mama333' console.log(obj) console.log(o)