码迷,mamicode.com
首页 > Web开发 > 详细

js深拷贝

时间:2020-03-31 21:07:40      阅读:66      评论:0      收藏:0      [点我收藏+]

标签:obj   style   ons   res   script   ems   let   element   ceo   

<script>
        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]);
    </script>

 

js深拷贝

标签:obj   style   ons   res   script   ems   let   element   ceo   

原文地址:https://www.cnblogs.com/zengsm/p/12607925.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!