This article is participating in the nuggets team number online activity, click to see the dachang spring recruiting positions

Concept: What is light copy?

  • Shallow copy: Only base types are copied from an object’s own properties. Complex types are referenced rather than traversed.
  • Deep copy: Iterates over properties of the object, and if an object is found in the property, further iterates.
let obj = {
  name: 'Steven Lee'.props: {
    static: true}}Copy the code

As a simple example, copy the obj object in the above code in both depth copy and light copy methods. Changing the obj name in the depth copy object will not affect the original object. A shallow copy object changes its object obj.props. Static (reference). A deep copy object has no effect on the object because it allocates extra memory.

Second, the implementation

1. The shallow copy

Just iterate over the first level object assignment

  • Standards implementation
function shallowCopy(obj) {
    if (typeofobj ! = ='object') return
    
    let newObj = obj instanceof Array ? [] : {}
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            newObj[key] = obj[key]
        }
    }
    return newObj
}
Copy the code
  • Es6 simple implementation

It’s really easy

letshallowCopyObj = {... obj}Copy the code

2. Deep copy

Traversal object, continue traversal when object is found in property

  • Standards implementation
function deepClone(obj) {
    if (typeofobj ! = ='object') return;
    var newObj = obj instanceof Array ? [] : {};
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            newObj[key] = typeof obj[key] === 'object'? deepClone(obj[key]) : obj[key]; }}return newObj;
}
Copy the code
  • Simple implementation
JSON.parse(JSON.stringify(obj))
Copy the code

Of course, neither approach takes into account the existence of built-in objects and functions in object properties.

Json.parse (json.stringify (obj)) generally solves most of the problems, but if this is not enough then the second parameter of json.stringify is used as an example

JSON.stringify({ a: 1.b: 2.c: undefined }) // "{"a":1,"b":2}"

function fn(key, value) {
  if (typeof value === "undefined") {
    value = 'undefined';
  }
  return value;
}

JSON.stringify({ a: 1.b: 2.c: undefined }, fn) // "{"a":1,"b":2,"c":"undefined"}"
Copy the code

In the same way, we can add some built-in object judgments and adaptations.

END