js使用递归来进行深拷贝

Daming 2018-08-15
1条评论 1,112 次浏览
Daming 2018-08-151条评论 1,112 次浏览
    function deepClone(origin, target) {

        var target = target || {};

        var toStr = Object.prototype.toString;
        var arrStr = "[object Array]";

        for (var prop in origin) {

            //判断是自身的属性
            if (origin.hasOwnProperty(prop)) {

                //判断是引用数据类型还是 原始数据类型
                if (origin[prop] !== null && typeof (origin[prop]) === "object") {

                    //判断是数组还是对象
                    if (toStr.call(origin[prop]) === arrStr) {
                        //数组
                        target[prop] = []

                    } else {
                        //对象
                        target[prop] = {}
                    }

                    deepClone(origin[prop], target[prop]);

                } else {
                    //原始数据类型
                    target[prop] = origin[prop];

                }


            }

        }


//如果没有传入第二个参数    给返回target
        return target;


    }

使用例子:

    var me = {
        name: "xiaoming",
        gender: "male",
        feature: ["handsome", "young", "hardworking"],
        address: {
            city: "chengdu",
            postcode: "610000",
        },
        girlFriend: {
            name: "xiaoli",
            gender: "female",
            feature: ["beauty", "cute"],
            address: {
                city: "chengdu",
                postcode: "610000",
            }
        }

    };


    var me2 = {};


    deepClone(me, me2);
1+

js使用递归来进行深拷贝” 有1条评论

发表评论

电子邮件地址不会被公开。