js 深拷貝和淺拷貝
阿新 • • 發佈:2021-06-17
1、淺拷貝
const obj = { name: '張三', age: 18, friend: {name: '小夏'} } const newObj = obj obj.age = 20 console.log(obj.age) // 20 console.log(newObj.age) // 20
直接用等於的方式進行拷貝,但是如果直接改變一個物件的某個屬性,另一個物件對應屬性值也會跟著改變
2、深拷貝
方法1
思路:如果不是物件、陣列或為null 直接拷貝,若是物件或陣列則迴圈拷貝每個屬性,這樣拷貝出來的變數和之前的變數改變值不會互相影響
const obj = { name: '張三', age: 18, friend: {name: '小夏'} } function deepClone(obj) { if(typeof(obj) != 'object' || typeof(obj) == null) { return obj }else { let result if(obj instanceof Array) { // 陣列 result = [] }else { // 物件 result = {} } for(let key in obj) { // 若直接等於,改變某個的friend另一個也會改變,故用遞迴 // result[key] = obj[key] result[key] = deepClone(obj[key]) } return result } } let newObj = deepClone(obj) newObj.age= 20 console.log(obj.age) // 18 console.log(newObj.age) // 20
方法二
思路:判斷是否是物件或陣列,若是轉成json字串再轉過,若不是直接返回
const obj = { name: '張三', age: 18, friend: {name: '小夏'} } function deepClone(obj) { if(typeof(obj) != 'object' || typeof(obj) == null) { return obj }else { return JSON.parse(JSON.stringify(obj)) } } let newObj = deepClone(obj) newObj.age = 20 console.log(obj.age) // 18 console.log(newObj.age) // 20