对象深复制
- 如果对象的属性值不是一个对象的引用
Object.assign
function (obj){
let newObj={}
for(var key in obj){
newObj[key]=obj[key]
}
return newObj;
}
2.即使对象的属性是对象也可以
function deepCopy(obj){
let newObj={}
for(var key in obj){
if(Object.prototype.toString.call(obj[key]) === "[object Object]"){
deepCopy(obj[key])
}else{
newObj[key]=obj[key]
}
return newObj
}
数组的深拷贝
- 循环拷贝
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.concat方法
var arr = [1,2,3,4,5]
var arr2 = arr.concat()
arr[2] = 5
console.log(arr)
console.log(arr2)
数组里面含有对象
let test = [1, 2, 3, { name: 'zhangsan', age: 23 }]
function deep(arr) {
let newArr = []
for (var i in arr) {
if (Object.prototype.toString.call(arr[i]) !== '[object Object]') {
newArr.push(arr[i])
} else {
newArr.push({ ...arr[i] })
}
}
return newArr
}
对象里面含有数组
let test = {
name: 2,
age: 3,
friend: [1, 2, 3]
}
function deep(obj) {
let newObj = {};
for (var i in obj) {
if (Object.prototype.toString.call(obj[i]) !== '[object Arrary]') {
newObj[i] = obj[i]
} else {
newObj[i] = [...obj[i]]
}
}
return newObj
}
对象数组混合
function deep(obj) {
let newObj = {};
for (var i in obj) {
if (Object.prototype.toString.call(obj[i]) !== '[object Arrary]' || Object.prototype.toString.call(arr[i]) !== '[object Object]') {
newObj[i] = obj[i]
} else {
newObj[i] = deep(obj[i])
}
}
return newObj
}
我也基本测试了,希望大佬们看到错误指出来