1、淺拷貝
Object.assign()
let a = {name:'le'}
let b = {age:8}
let d = {}
Object.assign(d,a,b)
console.log(d)
//或者
let d = Object.assign(a,b)
console.log(d)
複製程式碼
es6擴充套件符
let a = {name:'le'}
let b = {age:8}
let c = {...a,...b}
複製程式碼
2.深拷貝具有遞迴特性 JSON.parse(JSON.stringify())
let a = {name:'le',fn:function(){
console.log('fn')
}}
let e = JSON.parse(JSON.stringify(a))
console.log(e)
//{ name: 'le', age: 8 }
複製程式碼
如果物件裡沒有函式是可以達到目的的,但是物件裡有函式則會將其忽略
3.深拷貝 遞迴拷貝 解決函式屬性問題
function deepClone(obj){
if(obj === null) return null;
if(typeof obj !== 'object') return obj;
if(obj instanceof RegExp) return new RegExp(obj);
if(obj instanceof Date) return new Date(obj);
let newObj = new obj.constructor();
for(let key in obj){
newObj[key] = deepClone(obj[key]);
}
return newObj;
};
let o = {name:{name:1}}
let test = deepClone(o);
o.name.name = 'hello';
console.log(test);
複製程式碼