hi! Everybody is good! I am a medical examiner, a treatment department front-end code ape 🐒, dialogue with the code, listen to the voice of their heart, looking forward to everyone’s praise 👍 and attention ➕.

🙉 what is shallow copy

  • Shallow copy: Basic data types are copied without any impact. When reference types are copied, the source object is also modified.
  • Deep copy: A deep copy is an exact copy of a new object. It regenerates space in the heap area of memory, and changes to the copied object do not affect the source object

🙈 Common shallow copy mode

  1. Direct assignment
var user1 = {
    name : 'forensic'.age : 18
}
var user2 = user1;
user2.name = "Front-end hunter.";
console.log(user1); // {name: 'front-end hunter ', age: 18}
console.log(user2); // {name: 'front-end hunter ', age: 18}
Copy the code
  1. Object.assignmethods
var user1 = {
    name : "Forensic"
}
var user2 = Object.assign(user1, {age : 18}, {sex : 'male'});
console.log(user2); // { name: '法医', age: 18, sex: 'male' }
Copy the code

This method can be copied, but it is important to note that it is also a shallow copy when the attribute corresponds to a reference type:

var user1 = {
    name: "Forensic".like: {
        eat: "Noodles".sport: "Basketball",}};var user2 = Object.assign({}, user1);
console.log(user1); //{name: '法医', like: {eat: '面条', sport: '篮球'}}
console.log(user2); //{name: '法医', like: {eat: '面条', sport: '篮球'}}
user1.name = "Front-end hunter.";
console.log(user1); //{name: 'front end ', like: {eat:' noodles ', sport: 'basketball '}}
console.log(user2); //{name: '法医', like: {eat: '面条', sport: '篮球'}}
user1.like.eat = "Rice";
console.log(user1); / / {name: 'front end hunter, like: {eat:' rice ', sport: 'basket / / {name: "forensic", like: {eat:' noodles, sport: 'basketball'}} ball '}}
console.log(user2); //{name: '法医', like: {eat: '米饭', sport: '篮球'}}
Copy the code
  1. ES6Extended operator

The extension operator is a new syntax in ES6 that expands iterable objects in sequence. You can also copy objects using the ES6 extension operator, for example:

var user1 = {
    name: "Forensic".like: {
        eat: "Noodles".sport: "Basketball",}};varuser2 = {... user1};console.log(user1); //{name: '法医', like: {eat: '面条', sport: '篮球'}}
console.log(user2); //{name: '法医', like: {eat: '面条', sport: '篮球'}}
user1.name = "Front-end hunter.";
console.log(user1); //{name: 'front end ', like: {eat:' noodles ', sport: 'basketball '}}
console.log(user2); //{name: '法医', like: {eat: '面条', sport: '篮球'}}
user1.like.eat = "Rice";
console.log(user1); / / {name: 'front end hunter, like: {eat:' rice ', sport: 'basket / / {name: "forensic", like: {eat:' noodles, sport: 'basketball'}} ball '}}
console.log(user2); //{name: '法医', like: {eat: '米饭', sport: '篮球'}}
Copy the code

From the example above, we see that the ES6 extension operator is also a shallow copy.

  1. An array ofsliceconcatmethods

The above two methods, one is interception, one is concatenation, these two methods can also be used to copy arrays

Use the slice and concat methods to copy arrays
var user1 = ["Forensic", {eat:"Noodles".sport:"Basketball"}];

var user2 = user1.slice();
var user3 = user1.concat();
console.log(user1);//{name: '法医', like: {eat: '面条', sport: '篮球'}}
console.log(user2);//{name: '法医', like: {eat: '面条', sport: '篮球'}}
console.log(user3);//{name: '法医', like: {eat: '面条', sport: '篮球'}}
user1[0] = "Front-end hunter.";
console.log(user1);//{name: 'front end ', like: {eat:' noodles ', sport: 'basketball '}}
console.log(user2);//{name: '法医', like: {eat: '面条', sport: '篮球'}}
console.log(user3);//{name: '法医', like: {eat: '面条', sport: '篮球'}}
user1[1].eat = "Rice";
console.log(user1);//{name: 'front end ', like: {eat:' rice ', sport: 'basketball '}}
console.log(user2);//{name: '法医', like: {eat: '米饭', sport: '篮球'}}
console.log(user3);//{name: '法医', like: {eat: '米饭', sport: '篮球'}}
Copy the code
  1. jQueryIn the$.extend

$.extend(deep,target,object1,object2,….) In this way, you can implement shallow copy. The parameters are described as follows:

  • Deep:trueIndicates deep copy,falseShallow copy
  • Target: indicates the target object to be copied
  • Object1: object to be copied
 <body>
        <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script>         
            var user = {
                name: "Forensic".age: 18.like: {
                    eat: "Noodles".sport: "Basketball",}};var target = {};

            $.extend(target, user);
            target.name = "Front-end hunter.";
            console.log(user); //{name: 'front end ', like: {eat:' noodles ', sport: 'basketball '}}
            console.log(target); //{name: 'front end ', like: {eat:' noodles ', sport: 'basketball '}}
        </script>
    </body>
Copy the code

🐒 deep copy

  1. Json.parse (json.stringify (object to copy))

This is a popular way of making deep copies of objects. As follows:

var user = {
    name: "Forensic".age: 18.like: {
        eat: "Noodles".sport: "Basketball",}};var target = JSON.parse(JSON.stringify(user));
target.like.eat = "Rice";
console.log(user); //{name: '法医', like: {eat: '面条', sport: '篮球'}}
console.log(target); //{name: '法医', like: {eat: '米饭', sport: '篮球'}}
Copy the code

There is a drawback to this approach, however, and that is that the functions inside cannot be copied.

var user = {
    name: "Forensic".age: 18.like: {
        eat: "Noodles".sport: "Basketball",},say:function(){
        console.log("Front-end hunter."); }};var target = JSON.parse(JSON.stringify(user));
target.like.eat = "Rice";
console.log(user); / / {name: "forensic", like: {eat: 'noodles, sport:' basketball '}, say: f ()}
console.log(target); //{name: '法医', like: {eat: '米饭', sport: '篮球'}}
Copy the code
  1. jQueryIn the$.extend

As mentioned above, adding true enables shallow and deep copying.

 <body>
        <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script>         
            var user = {
                name: "Forensic".age: 18.like: {
                    eat: "Noodles".sport: "Basketball",}};var target = {};

            $.extend(true,target, user);
            target.like.eat = "Rice";
            console.log(user); //{name: '法医', like: {eat: '面条', sport: '篮球'}}
            console.log(target); //{name: '法医', like: {eat: '米饭', sport: '篮球'}}
        </script>
    </body>
Copy the code
  1. Handwritten recursive way to achieve deep copy
 // Origin indicates the object to be copied, and target indicates the target object
            function deepClone(origin, target) {
                var target = target || {}, // Error tolerance to prevent the user from not passing the target value
                    toStr = Object.prototype.toString,
                    arrAtr = "[object Array]";
                for (var prop in origin) {
                    // Iterate over the object
                    if (origin.hasOwnProperty(prop)) {
                        // Prevent getting the prototype chain attributes
                        if( origin[prop] ! = ="null" &&
                            typeof origin[prop] == "object"
                        ) {
                            // Check whether it is the original value
                            target[prop] =
                                toStr.call(origin[prop]) == arrAtr ? [] : {}; // Create the corresponding array or object
                            deepClone(origin[prop], target[prop]); // Recursive, in order to get the reference value inside the reference value
                        } else {
                            target[prop] = origin[prop]; // Is the original value, directly copy}}}return target;
            }
Copy the code

😊 ok, the above is my share, friends click a “like” and then go 👍 support oh ~ 😘, I will be more motivated 🤞