首页 > Web开发 > 详细

js 深拷贝

时间:2021-07-17 10:57:01      阅读:21      评论:0      收藏:0      [点我收藏+]
第一种方法 JSON.parse(JSON.stringify())
局限是无法克隆Function,undefined,null类型的
 1 let obj1= {
 2         name:‘Chandler Wong! ‘,
 3         feature:{
 4             hobby:[‘jazz‘,‘dance‘,‘guitar‘,‘football‘],
 5             language: [‘Chinese‘,‘English‘,‘Spanish‘],
 6             explain:function (){
 7                 let initData = ‘I like ‘
 8                 this.hobby.forEach(item => {
 9                     initData += item + ‘,‘
10                 })
11                 this.language.forEach((item,index) => {
12                     if(index < this.language.length - 1) {
13                         initData += item+‘,‘
14                     }else {
15                         initData+=‘and ‘+ item + ‘.‘
16                     }
17 
18                 })
19                 return initData
20             },
21             other:{
22                 liveCity:{
23                     residence1: ‘HuangGang‘,
24                     residence2:‘WuHan‘,
25                     address: ‘BeiJing‘
26                 }
27             }
28         },
29         major:[‘computer science‘,‘history‘],
30         introduce:function (){
31             return ‘Hello everybody,my name is ‘+this.name+this.feature.explain()
32         },
33         otherParam:[undefined,null,[],{},0,1,true,false]
34     }
35   // 第一种方法 JSON.parse(JSON.stringify())
36     const obj2=JSON.parse(JSON.stringify(obj1))
37     // JSON.parse(JSON.stringify())的局限是无法克隆类型为Function,undefined,null
38     console.log(‘【第一种方法 JSON.parse(JSON.stringify())】‘)
39     console.log(‘获取feature里边的explain方法‘,obj1.feature.explain())
40     console.log(‘获取introduce方法‘,obj1.introduce())
41     console.log(‘这是obj1‘,obj1)
42     console.log(‘这是拷贝自obj1的obj2‘,obj2)
技术分享图片

 

 第二方法,递归

 1 function deepClone(sourceObj){
 2         if(!sourceObj && typeof sourceObj != ‘object‘) {
 3             throw new Error(‘This is not object or sourceObj is empty!‘)
 4         }
 5         const targetObj = sourceObj.constructor === Array ? [] : {}
 6         Object.keys(sourceObj).forEach(item => {
 7             if(sourceObj[item] && typeof sourceObj[item] === ‘object‘){
 8                 targetObj[item] = deepClone(sourceObj[item])
 9             }else {
10                 targetObj[item] = sourceObj[item]
11             }
12         })
13         return targetObj
14     }
15    const obj3 = deepClone(obj1)
16     console.log(‘这是deepClone‘,obj3)

技术分享图片

 

 

 

 

js 深拷贝

原文:https://www.cnblogs.com/chandlerwong/p/15022032.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!