Home  >  Article  >  Web Front-end  >  Discussion on js deep copy examples

Discussion on js deep copy examples

小云云
小云云Original
2018-03-06 14:15:431373browse

Deep copy is a copy that copies the parent object to the child object, and the memory and subsequent operations of the two do not affect each other. This article mainly shares with you the discussion of js deep copy examples, hoping to help everyone.

(1) Method 1

function copy(obj1,obj2){
  var obj2=obj2||{}; 
  for(var name in obj1){    if(typeof obj1[name] === "object"){ //先判断一下obj[name]是不是一个对象
      obj2[name]= (obj1[name].constructor===Array)?[]:{}; 
      copy(obj1[name],obj2[name]); //然后来无限递归
    }else{
      obj2[name]=obj1[name];  //如果不是对象,直接赋值。
    }
  }  return obj2; 
}

Usage method:

var obj1 = {
    se:[{a:1,b:2},{c:3}],
    sa:{a:"g"},
    sc:function(){console.log(1)}
}var n_obj = copy(obj1,{})
console.log(n_obj)

(2) Method 2

function d_clone(obj) {
    return Object.getPrototypeOf(Object.create(obj));
}

Usage method:

var obj1 = {
    se:[{a:1,b:2},{c:3}],
    sa:{a:"g"},
    sc:function(){console.log(1)}
}var n2_obj = d_clone(obj1);
console.log(n2_obj)

(3) Method 3

JSON.parse(JSON.stringify(obj)

Description: The attributes of obj cannot contain functions.

(1) Method 1

function copy(obj1,obj2){
  var obj2=obj2||{}; 
  for(var name in obj1){    if(typeof obj1[name] === "object"){ //先判断一下obj[name]是不是一个对象
      obj2[name]= (obj1[name].constructor===Array)?[]:{}; 
      copy(obj1[name],obj2[name]); //然后来无限递归
    }else{
      obj2[name]=obj1[name];  //如果不是对象,直接赋值。
    }
  }  return obj2; 
}

Usage method:

var obj1 = {
    se:[{a:1,b:2},{c:3}],
    sa:{a:"g"},
    sc:function(){console.log(1)}
}var n_obj = copy(obj1,{})
console.log(n_obj)

(2) Method 2

function d_clone(obj) {
    return Object.getPrototypeOf(Object.create(obj));
}

Usage method:

var obj1 = {
    se:[{a:1,b:2},{c:3}],
    sa:{a:"g"},
    sc:function(){console.log(1)}
}var n2_obj = d_clone(obj1);
console.log(n2_obj)

(3) Method 3

JSON.parse(JSON.stringify(obj)

Description: The attributes of obj cannot contain functions.

Related recommendations:

Related recommendations:

In-depth understanding of JavaScript deep copy performance

What is js deep copy And shallow copy and its implementation

The difference between JavaScript shallow copy and deep copy

The above is the detailed content of Discussion on js deep copy examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn