<!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>
标签:const,oldObj,newObj,案例,obj,deepCopy,拷贝,js,color From: https://www.cnblogs.com/tomcat2022/p/17674558.html