Yeah deep copy and shallow copy, again finishing Review

What is shallow copy?

Take the form of an assignment of a copy of the referenced object, point to the same address, the object is to modify the original object will be modified

What is a deep copy?

A complete copy of the new object, the object is to modify the original object does not change

Several schemes shallow copy

1) assignment equal sign

let apple = { color: 'red'};
let newApple = apple;

2) Object.assign()

let apple = {
  size: {
    color: 'red'
  }
};
let newApple = Object.assign({}, apple);
newApple.size.color = 'green';
console.log(newApple.size.color); // green

3) Method Array concat

let apple = [1, {color: 'red'} ];
let newApple = apple.concat();
newApple[1].color = 'green';
console.log(apple[1].color) // green

4) slice array-

let apple = [1, {color: 'red'} ];
let newApple = apple.slice();
newApple[1].color = 'green';
console.log(apple[1].color) // green

Several deep copy program

1) only one object, the available Object.assign () implemented

let apple = { color: 'red' };
let newApple = Object.assign({},apple);
newApple.color = 'green';
console.log(apple); //{color: 'red'}

2) JSON.parse(JSON.stringify())

  • JSON.stringify with the object into a JSON string, then the JSON.parse () string parsed into objects
  • Array or object can be achieved a deep copy, but not handler
let apple = [1, {color: 'red'} ];
let newApple = JSON.parse(JSON.stringify(apple));
newApple[1].color = "green";
console.log (the Apple) // original object unchanged

 3) a recursive deep copy

  • Through the array, the innermost layer of the object until the basic data types, then replication
// In JavaScript, you want to decide which type of built-in value belongs to an object, the most likely way is by Object.prototype.toString method. 
Function dataType (value) {
   return Object.prototype.toString.call (value) .slice (. 8, -1 );
}
function clone(value) {
  let result, currentType  = dataType(value);
  if (currentType === 'Object') {
    result = {}
  } else if (currentType === 'Array') {
    result = []
  } else {
    return value
  }
  for (let i in value) {
    if (dataType(value[i]) === 'Object' || dataType(value[i]) === 'Array') {
      result[i] = clone(value[i])
    } else {
      result[i] = value[i]
    }
   }
   return result
 }
 was apple = {
   name: 'the' ,
   list: {
     id: [1, 2, 4],
     color: 'red'
   }
 }
 var newApple = clone(apple)

Guess you like

Origin www.cnblogs.com/Tiboo/p/12306442.html