1、数组浅拷贝
var arr = ["a", "b", "c"]
var arr2 = arr.slice( )
var arr3 = arr.concat( )
2、对象浅拷贝
var obj1 = {a: 1, b: 2}
var obj2 = {c: 3, d:4}
Object.assign(obj1, obj2)
obj1 // {a: 1, b: 2, c: 3, d:4}
3、深拷贝
缺点:不支持方法拷贝
var obj = {
name: "aa",
age: 18,
action: function( ){}
}
var obj1 = JSON.parse(JSON.stringify(obj))
console.log(obj1) //{name: "aa", age: 18}
4、深拷贝
function deep(dest, obj){
var o = dest;
for(var key in obj){
if(typeof obj[key] === 'object'){
o[key] = (obj[key].constructor === Array) ? [ ] : { }
deep(o[key], obj[key])
} else{
o[key] = obj[key]
}
}
return o;
}