JS学习笔记 - 深拷贝
function deepCopy(source,target){
for(let key in source){
if(source.hasOwnProperty(key)){
//只取非原型对象中的属性
if(source[key] && typeof source[key] === 'object'){
//判断该属性对应的值是是否为Array或object
//注意:typeof new Array和typeof new Object的结果均为object
//此处用于检测是否为引用类型
target[key] = source[key].constructor === Array ? [] : {
}
//此处通过该属性的constructor属性判断是Array还是Object并初始化目标对象对应属性
deepCopy(source[key],target[key])
//递归调用该函数,进行下一层拷贝
}else{
target[key] = source[key]
//非引用类型的属性直接拷贝
}
}
}
}
对Array和Object使用typeof时,返回的结果均为object