网络编程 发布日期:2024/11/13 浏览次数:1
本文实例讲述了JavaScript实现浅拷贝与深拷贝的方法。分享给大家供大家参考,具体如下:
平时使用数组复制时,我们大多数会使用‘=',这只是浅拷贝,存在很多问题。比如
let arr = [1,2,3,4,5]; let arr2 = arr; console.log(arr) //[1, 2, 3, 4, 5] console.log(arr2) //[1, 2, 3, 4, 5] arr[0] = 6; console.log(arr) //[6, 2, 3, 4, 5] console.log(arr2) //[6, 2, 3, 4, 5] arr2[4] = 7; console.log(arr) //[6, 2, 3, 4, 7] console.log(arr2) //[6, 2, 3, 4, 7]
很明显,浅拷贝下,拷贝和被拷贝的数组会相互受到影响。所以,必须要有一种不受影响的方法,那就是深拷贝。
深拷贝的实现方式有很多种。
一、for循环实现深拷贝
//for循环copy function copy(arr) { let cArr = [] for(let i = 0; i < arr.length; i++){ cArr.push(arr[i]) } return cArr; } let arr3 = [1,2,3,4]; let arr4 = copy(arr3) //[1,2,3,4] console.log(arr4) //[1,2,3,4] arr3[0] = 5; console.log(arr3) //[5,2,3,4] console.log(arr4) //[1,2,3,4]
二、slice方法实现深拷贝
//slice实现深拷贝 let arr5 = [1,2,3,4]; let arr6 = arr5.slice(0); arr5[0] = 5; console.log(arr5); //[5,2,3,4] console.log(arr6); //[1,2,3,4]
三、concat实现深拷贝
//concat实现深拷贝 let arr7 = [1,2,3,4]; let arr8 = arr7.concat(); arr7[0] = 5; console.log(arr7); //[5,2,3,4] console.log(arr8); //[1,2,3,4]
四、es6扩展运算实现深拷贝
//es6扩展运算实现深拷贝 let arr9 = [1,2,3,4]; let [...arr10] = arr9; arr9[0] = 5; console.log(arr9) //[5,2,3,4] console.log(arr10) //[1,2,3,4]
五、对象的循环深拷贝
// 循环copy对象 let obj = { id:'0', name:'king', sex:'man' } let obj2 = copy2(obj) function copy2(obj) { let cObj = {}; for(var key in obj){ cObj[key] = obj[key] } return cObj } console.log(obj) //{id: "0", name: "king", sex: "man"} console.log(obj2) //{id: "0", name: "king", sex: "man"}
六、对象转换成json实现深拷贝
//转换成json let obj3 = JSON.parse(JSON.stringify(obj)); console.log(obj3) //{id: "0", name: "king", sex: "man"}
七、es6扩展运算实现深拷贝
let {...obj4}= obj console.log(obj4) //{id: "0", name: "king", sex: "man"}
八、通用深拷贝
var clone = function (v) { var o = v.constructor === Array "object" "_blank" href="//www.jb51.net/Special/85.htm">javascript面向对象入门教程》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》希望本文所述对大家JavaScript程序设计有所帮助。