js 深拷贝

第一种方法 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)
js 深拷贝

 

 第二方法,递归

 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 深拷贝

 

 

 

 

js 深拷贝

上一篇:php冷门小知识


下一篇:PHP 语法