js 深拷贝

81 阅读1分钟
// 深拷贝函数
function deepCopy(obj){
	let newObj = Array.isArray(obj)?[]:{}//判断是否是数组
	for(let key in obj){
		// 排除null ''的影响
		if(obj.hasOwnProperty(key)){
			// typeof ['study', 'working', 'looking'] === 'object'
			if(obj[key] && typeof obj[key] === 'object'){
				newObj[key] = deepCopy(obj[key]) // 递归调用
			}else{
				newObj[key] = obj[key]
			}
		}
	}
	return newObj
}
let sourceObj = {
	name: 'winki',
	hobby: ['study', 'working', 'looking']
}
let anotherObj2 = {}
anotherObj2 = deepCopy(sourceObj)