Js commonplace of deep copy and shallow copy

Foreword

Often see in some website or blog "deep clone", "shallow clone" these two terms, in fact, this is well understood, we analyze here today js深拷贝和浅拷贝.

Shallow copy

Let's take an example to illustrate js shallow copy:

var n = {a: 1, b: 2}
var m = n
m.a = 12
console.log(n.a) // ?

Obviously the above n.avalue becomes 12, which is js shallow copy. Pointer to an object is copied only shallow copy, or essentially the same object.

Deep copy

Similarly, we still take an example to illustrate Shajiao js deep clone:

var n = {a: 1, b: 2}
var m = {a: n.a, b: n.b}
m.a = 12
console.log(n.a) // ?

Above output apparently still 1, m and n although all the attributes and values are all the same, but they are two different objects, they occupy two different memory addresses in the heap, which is deep copy. Deep copy is a complete copy of the new object out, they occupy two entirely different memory addresses in the heap memory.

js achieve deep copy

Simple one-dimensional data structure

  1. Manual direct assignment

Examples of the above deep copy

  1. ES6 using the Object.assign()method

const obj = {name: 'cc', age: 24}
const newObj = Object.assign({}, obj)
obj.name = 'cc1'
newObj.name ? // cc

And more than two-dimensional data structure

  1. Simple and crude JSON.parse(JSON.stringify(obj))way: .

Cons: It would be for the regular expression type, function types can not be deep copy, but will directly lose the corresponding value, and that it will abandon the object constructor.

var obj = { a: {a: "cc"}, b: 123 }
var newObj = JSON.parse(JSON.stringify(obj))
newObj.b = 1234
console.log(obj)   // {a: {a: 'cc'}, b: 123}
console.log(newObj);    // {a: {a: 'cc'}, b: 1234}
  1. Use jQuery

// 浅拷贝
var newObj = $.extend({}, obj)

// 深拷贝
var newObj = $.extend(true, {}, obj) // 要求第一个参数必须为true
  1. Yourself achieve a simple deep copy function
function deepClone(obj){
  if(typeof obj !== "object" || obj === null) return    
  let newObj = obj instanceof Array ? [] : {}
  for(let key in obj){
     if(obj.hasOwnProperty(key)){
        newObj[key] = typeof obj[key] === "object" && obj[key] !== null ? deepClone(obj[key]) : obj[key]
    }      
  }  
  return newObj
}
let obj = {a: 1, b: function(){}, c: {d: 2}}
deepClone(obj)  // {a: 1, b: function(){}, c: {d: 2}}

For deep copy is the most common of these methods is, of course, there are other libraries, for example deepCopy, lodashand so on, will not go into here.

Guess you like

Origin www.cnblogs.com/dreamcc/p/11588562.html