Front-end interviews must involve recursive deep copy handwriting

<!DOCTYPE html>

<html>

    <head>

        <meta charset="utf-8">

        <title></title>

    </head>

    <body>

        <script>

            // js copies an object

            // Deep copy, the target object and the source object are cut off from each other

            var obj1 = {name:"mumu",age:18,friend:["小红","小青",{name:"小蓝",job:"teacher"}],say(){alert(" Hello, I am "+this.name)}};

             // If it is an array, recursion is required. If it is an object, recursion is required. If it is a value type, recursion ends.

             function deepCopy(obj){

                 if(typeof obj=="object"&&obj!=null){

                     // reference type

                     var temp = null;

                     // if it is an array

                     if(obj instanceof Array){

                         //The result to be returned should be an array

                        temp = [];

                        // Recursively copy array

                        for(var i=0;i<obj.length;i++){

                            // temp[i] = obj[i] // x is an ordinary shallow copy

                            temp[i] = deepCopy(obj[i]); // Recursive copy

                            // The function calls itself and returns the result of copy obj[i]

                        }

                     }else{

                         //The returned result is the object

                         temp = {};

                        // Recursively copy objects

                        for(var k in obj){

                            temp[k] = deepCopy(obj[k]);

                        }

                     }

                     //return results

                     return temp;

                 }else{

                     // Non-reference type or other

                     return obj;

                 }

             }

             var obj2 = deepCopy(obj1);

           

        </script>

    </body>

</html>

Guess you like

Origin blog.csdn.net/lyinshaofeng/article/details/127911054