1、第一步:js深拷贝和浅拷贝的概念和区别。1.浅拷贝拷贝就是把父对像的属性,全部拷贝给子对象。此时子对象拷贝的是父对象的地址,子父对象相互影响。2.深拷贝就是把父对象的属性中的值拷贝给子对象此时不论父对象如何改变都不会再影响到子对象。
2、第二步:测试浅拷贝。我们借助于谷歌浏览器控制台实现浅拷贝的测试,首先声明对象:var father={familyName:"张"}; var son={};拷贝son=father此时打印,son和father的familyName都是张将father的familyName改为“李”,则son的familyName也变为了“李”。这就是浅拷贝,拷贝的是存储变量的地址会互相影响。
3、第三步:浅拷贝的实现第一种:借助于js的JSON对象的两个函数JSON.stringify猾诮沓靥(father)将一个json对象转为json字符串JSON.parse(str)将一个枣娣空郅json字符串转为json对象它的实现原理是现将对象转为一个基本数据类型,在执行拷贝,不过这个只是适用于json格式的数据对其它情况不一定都能满足。测试如下:var father={familyName:"张"};var son={};son = JSON.parse(JSON.stringify(father));father.familyName="李"son.familyName
4、第四步:借助于for 循环实现数组的深拷贝具体代码和实现:如下var father = [1,2,3荑樊综鲶,4,5]var son = copyArr(father)function copyArr(father) { let res = [] for (let i = 0; i < arr.length; i++) { res.push(father[i]) } return res}console.log(father)console.log(son)father[2] = 5console.log(father)console.log(son)
5、第五步:借助于slice 方法实现数组的深拷贝具体代码如下所示:var father = [1,2,3,4,5]var son = father.slice(0)console.log(father)console.log(son)father[2] = 5console.log(father)console.log(son)
6、第六步:借助于concat 方法实现数组的深拷贝具体代码如下所示:var father = [1,2,3,4,5]var son = father.concat()console.log(father)console.log(son)father[2] = 5console.log(father)console.log(son)
7、第七步:使用ES6扩展运算符实现数组的深拷贝具体代码如下所示:var father = [争犸禀淫'张三','李四','刘德华',泌驾台佐39;周润发']var [ ...son ] = fatherconsole.log(father)console.log(son)father[2] = 5console.log(father)console.log(son)