js深拷贝案例
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="" />
</head>
<style>
.item{
color:red;
background-color: antiquewhite;
border:1px solid burlywood;
width:100px;
height:300px;
}
</style>
<body>
<div></div>
</body>
<script>
const obj={
uname:'pink',
age:18,
}
const o={}
function deepCopy(newObj,oldObj){
for(let k in oldObj){
newObj[k]=oldObj[k];
}
}
deepCopy(o,obj)
console.log(o);
</script>
</html>
带数组模式的的深拷贝
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="" />
</head>
<style>
.item{
color:red;
background-color: antiquewhite;
border:1px solid burlywood;
width:100px;
height:300px;
}
</style>
<body>
<div></div>
</body>
<script>
const obj={
uname:'pink',
age:18,
hobby:['乒乓球','篮球'],
}
const o={}
function deepCopy(newObj,oldObj){
for(let k in oldObj){
if(oldObj[k] instanceof Array){
newObj[k]=[];
deepCopy(newObj[k],oldObj[k]);
}else{
newObj[k]=oldObj[k];
}
}
}
deepCopy(o,obj)
console.log(o);
</script>
</html>
带有数组 和对象的 深拷贝案例
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="" />
</head>
<style>
.item{
color:red;
background-color: antiquewhite;
border:1px solid burlywood;
width:100px;
height:300px;
}
</style>
<body>
<div></div>
</body>
<script>
const obj={
uname:'pink',
age:18,
hobby:['乒乓球','篮球'],
family:{
name:'小秋',
age:19,
}
}
const o={}
function deepCopy(newObj,oldObj){
for(let k in oldObj){
if(oldObj[k] instanceof Array){
newObj[k]=[];
deepCopy(newObj[k],oldObj[k]);
}else if(oldObj[k] instanceof Object){
newObj[k]={};
deepCopy(newObj[k]=oldObj[k])
}else{
newObj[k]=oldObj[k];
}
}
}
deepCopy(o,obj)
console.log(o);
</script>
</html>
利用 转化字符串来实现 但是方法好像无法复制啊
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="" />
</head>
<style>
.item{
color:red;
background-color: antiquewhite;
border:1px solid burlywood;
width:100px;
height:300px;
}
</style>
<body>
<div></div>
</body>
<script>
const obj={
uname:'pink',
age:18,
hobby:['乒乓球','篮球'],
family:{
name:'小秋',
age:19,
},
eat:function(){
alert('ddd');
}
}
const aa= JSON.stringify(obj);
console.log(aa);
const newObj=JSON.parse(aa);
console.log(newObj);
</script>
</html>
事常与愿违,事亦在人为