美文网首页
js深拷贝

js深拷贝

作者: 事在人为s | 来源:发表于2020-04-13 09:48 被阅读0次

        function deepClone(obj) {
            if (typeof obj != 'object' || obj == null) {
                return obj;
            }
            let result;
            if (obj instanceof Array) {
                result = [];
            } else {
                result = {};
            }
            for (const key in obj) {
                if (obj.hasOwnProperty(key)) {
                    const element = obj[key];
                    result[key] = deepClone(element);
                }
            }
            return result;
        }


        let obj = {
            name: "伍子胥",
            girl: {
                name: 'any',
                items: [1, 2, 3]
            }
        };
        let obj2 = deepClone(obj);
        obj2.girl.name = 'abc';
        obj2.girl.items[0] = 999;
        console.log(obj.girl.name);
        console.log(obj.girl.items[0]);

相关文章

网友评论

      本文标题:js深拷贝

      本文链接:https://www.haomeiwen.com/subject/wwgwmhtx.html