#### 1. 淺拷貝 --- **淺拷貝: 只是拷貝了基本類型的數(shù)據(jù),而引用類型的數(shù)據(jù),復(fù)制后還會(huì)發(fā)生引用** 示例數(shù)據(jù) ```javascript const user = { name: 'liang', age: 23 } ``` 在 js 中,引用類型的數(shù)據(jù)使用 **=** 進(jìn)行賦值時(shí),傳遞的都是引用,而并非其對(duì)應(yīng)的值,這樣賦值并沒有真正的拷貝數(shù)據(jù) ```javascript const user1 = user user1.name = 'my name is liang' console.log(user) // {name: 'my name is liang', age: 23} ``` 我們有以下幾種方案可以進(jìn)行淺拷貝 ```javascript // 方案一: 使用 for in 循環(huán)取出屬性和值,賦值給一個(gè)新的對(duì)象 const obj = {} for (const key in user) { obj[key] = user[key] } // 方案二: 使用 Object.assign() 進(jìn)行淺拷貝 const obj = Object.assign({}, user) // 方案三: 使用展開語法 const obj = { ...user } ``` 淺拷貝存在的問題: 當(dāng)屬性值存在引用類型數(shù)據(jù)時(shí),則拷貝的是引用,并不是真正的拷貝,要解決這個(gè)問題則需要深拷貝 ```javascript const user = { name: 'liang', info: { age: 23, } } const profile = { ...user } profile.name = 'zhang' profile.info.age = 18 console.log(user) // {name: 'liang', info: {age: 18}} console.log(profile) // {name: 'zhang', info: {age: 18}} ``` #### 2. 深拷貝 --- **深拷貝: 拷貝基本類型和引用類型的數(shù)據(jù),而不是拷貝引用類型的引用** 數(shù)據(jù)示例 ```javascript const user = { name: 'liang', info: { age: 23 }, array: ['html', 'css', 'javascript'], show(name) { return `${name} call show method` } } ``` 深拷貝對(duì)象-迭代遞歸法 ```javascript // 深拷貝對(duì)象 function copy(object) { let data = object instanceof Array ? [] : {} for (const [key, value] of Object.entries(object)) { data[key] = typeof value == 'object' ? copy(value) : value; } return data } // 拷貝對(duì)象 const profile = copy(user) // 修改通過拷貝得到的變量不會(huì)影響原數(shù)據(jù) profile.name = 'zhang' profile.info.age = 18 profile.array.push('profile push data') profile.show = () => 'profile update show method' console.log(user) console.log(profile) ```