• 技术文章 >web前端 >js教程

    JS 深拷贝的三种实现方式

    GuanhuiGuanhui2020-05-30 15:38:13原创4659

    JS 深拷贝的三种实现方式

    1、将对象转换为JSON字符串形式,再将其转换为原生JS对象;

    //_tmp和result是相互独立的,没有任何联系,有各自的存储空间。
    let deepClone = function (obj) {
        let _tmp = JSON.stringify(obj);//将对象转换为json字符串形式
        let result = JSON.parse(_tmp);//将转换而来的字符串转换为原生js对象
        return result;
    };
    
    let obj1 = {
        weiqiujaun: {
            age: 20,
            class: 1502
        },
        liuxiaotian: {
            age: 21,
            class: 1501
        }
    };
    
    let test = deepClone(obj1);
    console.log(test);

    2、使用JS中的for循环实现遍历和复制;

    function deepClone(obj) {
        let result = typeof  obj.splice === "function" ? [] : {};
        if (obj && typeof obj === 'object') {
            for (let key in obj) {
                if (obj[key] && typeof obj[key] === 'object') {
                    result[key] = deepClone(obj[key]);//如果对象的属性值为object的时候,递归调用deepClone,即在吧某个值对象复制一份到新的对象的对应值中。
                } else {
                    result[key] = obj[key];//如果对象的属性值不为object的时候,直接复制参数对象的每一个键值到新的对象对应的键值对中。
                }
    
            }
            return result;
        }
        return obj;
    }
    
    let testArray = ["a", "b", "c", "d"];
    let testRes = deepClone(testArray);
    console.log(testRes);
    console.log(typeof testRes[1]);
    
    let testObj = {
        name: "weiqiujuan",
        sex: "girl",
        age: 22,
        favorite: "play",
        family: {brother: "son", mother: "haha", father: "heihei"}
    };
    let testRes2 = deepClone(testObj);
    testRes2.family.brother = "weibo";
    console.log(testRes2);

    3、利用数组的“Array.prototype.forEach”方法进行复制即可实现深拷贝。

    let deepClone = function (obj) {
        let copy = Object.create(Object.getPrototypeOf(obj));
        let propNames = Object.getOwnPropertyNames(obj);
        propNames.forEach(function (items) {
            let item = Object.getOwnPropertyDescriptor(obj, items);
            Object.defineProperty(copy, items, item);
    
        });
        return copy;
    };
    
    let testObj = {
        name: "weiqiujuan",
        sex: "girl",
        age: 22,
        favorite: "play",
        family: {brother: "wei", mother: "haha", father: "heihei"}
    }
    let testRes2 = deepClone(testObj);
    console.log(testRes2);

    推荐教程:《JS教程

    以上就是JS 深拷贝的三种实现方式的详细内容,更多请关注php中文网其它相关文章!

    声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理
    专题推荐:php
    上一篇:js中的typeof和instanceof和===的区别 下一篇:js怎么移除css属性
    大前端线上培训班

    相关文章推荐

    • 第1篇快速入门—js基础实战中的Date、Math、Global对象• 面试与笔试中常考的js基础知识:ES6 Promise的用法• (常见面试题)js基础 从setTimeout 到 js的异步原理• JS基础知识必备—常见面试题目系统整理• js基础心法之数据类型

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网