数组深拷贝
1、for循坏
var arr = [1,2,3,4,5]
var arr2 = copyArr(arr)
function copyArr(arr) {
let res = []
for (let i = 0; i < arr.length; i++) {
res.push(arr[i])
}
return res
}
2、数组slice 方法
var arr = [1,2,3,4,5]
var arr2 = arr.slice(0)
arr[2] = 5
console.log(arr)
console.log(arr2)
3、数组concat 方法
var arr = [1,2,3,4,5]
var arr2 = arr.concat()
arr[2] = 5
console.log(arr)
console.log(arr2)
4、ES6扩展运算符实现数组的深拷贝
var arr = [1,2,3,4,5]
var [ ...arr2 ] = arr
arr[2] = 5
console.log(arr)
console.log(arr2)
对象深拷贝
1、万能的for循环实现对象的深拷贝
var obj = {
name: 'FungLeo',
sex: 'man',
old: '18'
}
var obj2 = copyObj(obj)
function copyObj(obj) {
let res = {}
for (var key in obj) {
res[key] = obj[key]
}
return res
}
2、转换成json再转换成对象实现对象的深拷贝
var obj = {
name: 'FungLeo',
sex: 'man',
old: '18'
}
var obj2 = JSON.parse(JSON.stringify(obj))
3、扩展运算符实现对象的深拷贝
var obj = {
name: 'FungLeo',
sex: 'man',
old: '18'
}
var { ...obj2 } = obj
obj.old = '22'
console.log(obj)
console.log(obj2)
4、深拷贝函数
var obj1 = {
country: '中国',
city: ['北京', '上海', '广州'],
skincolr: 'yellow',
date: 2007,
friend: {
name: "dot",
age: null
}
}
//深复制,要想达到深复制就需要用递归
function deepCopy(oldObj, newObj) {
var newObj = newObj || {};
for (var i in oldObj) {
//用instanceof排除null的情况
if (oldObj[i] instanceof Object) {
//要考虑深复制问题了
if (oldObj[i].constructor === Array) {
//这是数组
newObj[i] = [];
} else {
//这是对象
newObj[i] = {};
}
deepCopy(oldObj[i], newObj[i]);
} else {
newObj[i] = oldObj[i];
}
}
return newObj;
}
var obj2 = { name: 'obj2'};
obj2 = deepCopy(obj1, obj2);
console.log(obj2);
数组,对象深拷贝函数
function deepClone(obj) {
let objClone = Array.isArray(obj) ? [] : {}
if (obj && typeof obj == 'object') {
for (key in obj) {
// for-in遍历的是原型链,需要用hasOwnProperty 判断是否是自有属性
if (obj.hasOwnProperty(key)) {
// 判断obj子元素是否为对象。如果是,则递归复制
if (obj[key] && obj[key] === 'object') {
objClone[key] = deepClone(obj[key])
} else {
// 如果不是,简单复制
objClone[key] = obj[key]
}
}
}
return objClone
} else {
//如果obj不是对象,那么直接返回值就可以了
return obj
}
}