js 两行代码实现完全深拷贝

412 阅读1分钟
function deepCopy(obj){
	Object.keys(obj).forEach(item=>obj[item] = deepCopy(obj[item]))
	return typeof obj == "object" ? (obj.constructor == Array ? [...obj] : {...obj}) : obj;
}

用到了es6的拓展运算符可能兼容性不佳

或者这样

function deepCopy(obj){
	if(typeof obj == "object"){
		let result = obj.constructor == Array ? [] : {};
		Object.keys(obj).forEach(item=>result[item] = deepCopy(obj[item]))
		return result;
	} 
	else return obj;
}

我知道你最喜欢的还是 JSON.parse(JSON.stringify(obj))