1.递归
1 copyFun (obj) { 2 let newObj = null; 3 // typeof null = 'object' 规避null 4 if (typeof (obj) == 'object' && obj !== null) { 5 newObj = obj instanceof Array ? [] : {} 6 for (var i in obj) { 7 newObj[i] = this.copyFun(obj[i]) 8 } 9 } else { 10 newObj = obj 11 } 12 return newObj 13 }
2.JSON格式转换
let newObj = JSON.parse(JSON.stringify(obj))
缺点:1.function对象无法被拷贝 2.无法拷贝copyObj对象原型链上的属性和方法
3.Object.assign()方法
Object.assign( newObj,obj )
缺点:只能深拷贝一层