<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>深浅拷贝</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script>
var oldobj={
name:'呀呀呀',
older:{
age:13
},
color:['pink','red','orange']
}
var newobj={};
//js原生语法浅拷贝
/*for(var i in oldobj){
newobj[i]=oldobj[i];
}
newobj.older.age=23;
console.log(oldobj);*/
//js语法糖浅拷贝
/*Object.assign(newobj,oldobj);
newobj.older.age=23;
console.log(oldobj);*/
//js语法糖深拷贝
function deepCopy(newobj,oldobj){
for(k in oldobj){
var item=oldobj[k];
if(item instanceof Array){
newobj[k]={};
deepCopy(newobj[k],item);
}else if(item instanceof Object){
newobj[k]=[];
deepCopy(newobj[k],item)
}else{
newobj[k]=oldobj[k];
}
}
}
deepCopy(newobj,oldobj);
newobj.older.age=23;
console.log(oldobj);
//jQuery浅拷贝
/* $.extend(newobj,oldobj);
newobj.older.age=23;
console.log(oldobj);*/
//jQuery深拷贝
/*$.extend(true,newobj,oldobj);
newobj.older.age=23;
console.log(oldobj);*/
</script>
</body>
</html>
javascript中深拷贝与浅拷贝
最新推荐文章于 2022-07-27 10:58:51 发布