directory

  1. Stack overflow when new Map() is used as an internal function variable
  2. [recursive] New Map() solves the problem of circular references when used as a function parameter
  3. Recursive assignment process

Stack overflow when new Map() is used as a function internal variable

// Use the Map function
function deepcopy(obj, map = new Map(a)){
    if(typeofobj ! = ='object') {return}
    let res =  Array.isArray(obj) ? [] : {};if(map.get(obj)){ 
      return map.get(obj); 
    } 
    map.set(obj,res);
    //console.log('map', map);
    for(let key in obj){
        if(obj.hasOwnProperty(key)){
            if(typeof obj[key] === 'object'){
                res[key] = deepcopy(obj[key]);
             }else{ res[key] = obj[key]; }}}return res;
};

var obj={a:1.b:2}
obj.c=obj
var deepcopyObj2 = deepcopy(obj);
//deepcopyObj2.c.c1=666
console.log(obj,deepcopyObj2);
Copy the code

[recursive] new Map() solves the problem of circular references

WeakMap() works just as well

Only two changes were made in the comments

function deepcopy(obj, map = new Map(a)){ // Convert a function variable to an argument
    if(typeofobj ! = ='object') {return}
    let res =  Array.isArray(obj) ? [] : {};if(map.get(obj)){ 
      return map.get(obj); 
    } 
    map.set(obj,res);
    //console.log('map', map);
    for(let key in obj){
        if(obj.hasOwnProperty(key)){
            if(typeof obj[key] === 'object'){
                res[key] = deepcopy(obj[key],map); // Change this, pass map
             }else{ res[key] = obj[key]; }}}return res;
};

var obj={a:1.b:2}
obj.c=obj
var deepcopyObj2 = deepcopy(obj);
console.log(obj,deepcopyObj2);

Copy the code

Three recursive assignment process

From the inside out, depth takes precedence

function deepcopy(obj, map = new Map(a)){  
    if(typeofobj ! = ='object') {return}
    let res =  Array.isArray(obj) ? [] : {};if(map.get(obj)){ 
      return map.get(obj); 
    } 
    map.set(obj,res);
    
    console.log('map:::', map);
    for(let key in obj){
        if(obj.hasOwnProperty(key)){
            if(typeof obj[key] === 'object'){
                res[key] = deepcopy(obj[key],map);
             }else{ res[key] = obj[key]; }}}console.log(res);
    return res;
};

var obj={a:1.b:2.c: {},d: {e: {f: {i: {g:3}}}}}
obj.c=obj
var deepcopyObj2 = deepcopy(obj);

Copy the code

reference

conclusion

  • What causes stack overflow when new Map() is used as a function internal variable? Why is it ok as a parameter?
  • There are a number of methods that are already packaged in JS:concat().filter().slice().map()Etc., while modifying the array,The original array will not be modified, butReturns a new array. But thisIt's not really a deep copy, is still a shallow copy when an array is nested with array objects,Changes to nested arrays still affect the values of the original array