zoukankan      html  css  js  c++  java
  • 使用遍历的方法实现对对象的深拷贝

    本文转自:http://www.cnblogs.com/baiyangyuanzi/p/6519765.html

    测试代码:

    function getType(o){
        var _t;
        return ((_t = typeof(o)) == "object" ? o==null && "null" || Object.prototype.toString.call(o).slice(8,-1):_t).toLowerCase();
    }
    function extend(destination,source){
        for(var p in source){
            if(getType(source[p])=="array"||getType(source[p])=="object"){
                destination[p]=getType(source[p])=="array"?[]:{};
                arguments.callee(destination[p],source[p]);
            }else{
                destination[p]=source[p];
            }
        }
    }
    
    var test={
        a:"ss",
        b:"dd",
        c:[
            {d:"css",e:"cdd"},
            {
                m:"ff",
                n:[
                    {kk:"11",jj:"22"},
                    {ll:"44"}
                ]
            }
        ]
    };
    
    var test1={};
    extend(test1,test);
    console.log(test);
    console.log(test1);
    test1.c[1].n[0].kk="change"; //改变test1的c属性对象的d属性
    console.log(test);
    console.log(test1);
    console.log(test.c[1].n[0]);
    console.log(test1.c[1].n[0]);

    测试结果:

     从测试结果可以看到,通过使用这个遍历的方法,成功将对象test深拷贝复制一份,得到test1。并且更改test1对象的属性,并不会对test对象产生影响。

  • 相关阅读:
    Validate US Telephone Numbers
    7月份总结
    Arguments Optional
    Everything Be True
    手机开发网页模板(20140124)
    整站开发初始化
    switch滑动开关
    js 面向对象
    Bootstrap 导航栏
    Bootstrap 标签页
  • 原文地址:https://www.cnblogs.com/sghy/p/7323855.html
Copyright © 2011-2022 走看看