# 深拷贝浅拷贝的区别

·  阅读 200

## 一.浅拷贝

#### 在js中，浅拷贝的方法有以下几种：

Object.assign

``````var obj={
age:18,
names:{
name1:'lixi',
name2:'xixi'
},
hobby:['sing','shopping']
}
var newObj = Object.assign({},fxObj)

slice()

``````  const fxArr = ['One','Two','Three']
const fxArrs = fxArr.slice(0)
fxArrs[1] = 'love'
console.log(fxArr)  // ['One','Two','Three']
console.log(fxArrs)  //['One','love','Three']

concat()

``````  const fxArr = ['One','Two','Three']
const fxArrs = fxArr.concat()
fxArrs[1] = 'love';
console.log(fxArr) // ['One', 'Two', 'Three']
console.log(fxArrs) // ['One', 'love', 'Three']

``````    const fxArr = ["One", "Two", "Three"]
const fxArrs = [...fxArr]
fxArrs[1] = "love";
console.log(fxArr) // ["One", "Two", "Three"]
console.log(fxArrs) // ["One", "love", "Three"]

## 二、深拷贝

#### 常见的深拷贝的方法有以下几种：

_.cloneDeep()

``````    const _ = require('lodash');
const obj1 = {
a: 1,
b: { f: { g: 1 } },
c: [1, 2, 3]
};
const obj2 = _.cloneDeep(obj1);
console.log(obj1.b.f === obj2.b.f);// false

jQuery.extend()

``````    const \$ = require('lodash');
const obj1 = {
a: 1,
b: { f: { g: 1 } },
c: [1, 2, 3]
};
const obj2 =\$.extend(true, {}, obj1);
console.log(obj1.b.f === obj2.b.f);// false

JSON.stringify()

``````const obj2=JSON.parse(JSON.stringify(obj1));

• 但是这种方法，会忽略undefined、symbol和函数
``````    const obj = {
name: 'A',
name1: undefined,
name3: function() {},
name4:  Symbol('A')
}
const obj2 = JSON.parse(JSON.stringify(obj));
console.log(obj2); // {name: "A"}