浅克隆
可直接调用Object.assign()实现
深克隆
常见深克隆
//克隆函数
function deepClone(obj, newObj) {
if (obj instanceof Array) {
newObj = []
return deepCloneArray(obj, newObj)
} else if (obj instanceof Object) {
newObj = []
return deepCloneObject(obj, newObj)
} else {
return newObj = obj
}
}
//克隆对象
function deepCloneObject(obj, newObj) {
for (var temp in obj) {
if (obj.hasOwnProperty(temp)) {
if (obj[temp] instanceof Object || obj[temp] instanceof Array) {
var tempNewObj = {}
newObj[temp] = deepClone(obj[temp], tempNewObj)
} else {
newObj[temp] = obj[temp]
}
}
}
return newObj
}
//克隆数组
function deepCloneArray(arr, newArr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] instanceof Object || arr[i] instanceof Array) {
var tempNewArr
newArr[i] = deepClone(arr[i], tempNewArr)
} else {
newArr[i] = arr[i]
}
}
return newArr
}
便捷方法
const newObj = JSON.parse(JSON.stringify(oldObj))
- 无法实现对函数、RegExp等特殊对象的克隆
- 会抛弃对象的constructor,所有的构造函数会指向Object
- 对象有循环引用,会报错