项目中,一般会用loadsh库,地址:https://github.com/lodash/lodash
浅拷贝方法:_.clone 深拷贝方法:_.cloneDeep, _.cloneDeepWith
参考链接:https://blog.csdn.net/SinceroTu/article/details/78055278
浅拷贝,
function _shallowCopy(obj){
// 判断是否是数组或者对象
if(typeof obj !== 'object'){
return
}
let newObj = obj instanceof Array ? [] : {}
for(let key in obj){
if(obj.hasOwnProperty(key)){
newObj[key] = obj[key]
}
}
return newObj
}
深拷贝,
function _deepCopy(obj){
// 判断是否是数组或者对象
if(typeof obj !== 'object'){
return
}
let newObj = obj instanceof Array ? [] : {}
for(let key in obj){
if(obj.hasOwnProperty(key)){
newObj[key] = typeof obj[key] === 'object' ? _deepCopy(obj[key]) : obj[key]
}
}
return newObj
}