深拷贝
function deepClone ( obj ) {
let objClone = Array. isArray ( obj) ? [ ] : { }
if ( obj && typeof obj === "object" ) {
for ( key in obj) {
if ( obj. hasOwnProperty ( key) ) {
if ( obj[ key] && typeof obj[ key] === "object" ) {
objClone[ key] = deepClone ( obj[ key] )
} else {
objClone[ key] = obj[ key]
}
}
}
}
return objClone;
}
let a = [ 1 , 2 , 3 , 4 ] ;
let b = deepClone ( a) ;
a[ 0 ] = 2 ;
console. log ( a, b) ;
function deepClone ( obj ) {
let _obj = JSON . stringify ( obj) ;
let objClone = JSON . parse ( _obj) ;
return objClone;
}
let a= [ 0 , 1 , [ 2 , 3 ] , 4 ] ,
b= deepClone ( a) ;
a[ 0 ] = 1 ;
a[ 2 ] [ 0 ] = 1 ;
console. log ( a, b) ;
浅拷贝
let a = { name : '师傅' } ;
let b = {
age : 19 ,
sex : "男" ,
arr : [ 1 , 2 , 3 ] ,
habit : {
play : "内卷"
}
}
let c = Object. assign ( { } , a, b) ;
c. age = 20 ;
c. arr[ 1 ] = 10 ;
console. log ( c) ;