JavaScript浅拷贝与深拷贝 JavaScript实现浅拷贝与深拷贝的方法分析
king-w 人气:0本文实例讲述了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 ? [] : {}; for(var i in v){ o[i] = typeof v[i] === "object" ? clone(v[i]) : v[i]; } return o; }
总结:深刻理解javascript的深浅拷贝,可以灵活的运用数组,并且可以避免很多bug。
希望本文所述对大家JavaScript程序设计有所帮助。
加载全部内容