潜拷贝,深拷贝

var obj1 = {
    'name' : 'zhangsan',
    'age' :  '18',
    'language' : [1,[2,3],[4,5]],
};

var obj2 = obj1;


var obj3 = shallowCopy(obj1);
function shallowCopy(src) {
    var dst = {};
    for (var prop in src) {
        if (src.hasOwnProperty(prop)) {
            dst[prop] = src[prop];
        }
    }
    return dst;
}

obj2.name = "lisi";
    obj2['zzz'] = "zzz";
obj3.age = "20";

obj2.language[1] = ["二","三"];
obj3.language[2] = ["6","五"];
obj3['xxx'] =1;
console.log(obj1);  
console.log(obj2);
console.log(obj3);

var  a='xxxxx';
var n =  a;
a = 'v';
console.log(a);
console.log(n);

var a = [1,2];
var n = a;
a[0] = 3;
n[1] = 4;
console.log(a);
console.log(n);

var a = 100;
var b = a;

a++;
console.log(a);
    console.log(b);


function shallowCopy(obj){
    var newObj = {};
    for(var key in obj){
        if(obj.hasOwnProperty(key)){
            newObj[key] = obj[key];
        }
    }
    return newObj;
}

var obj1 = {
    xxx:[1,2,3],
    name:'test'
}

var obj2 = {
    xxx:[1,2,3],
    name:'test'
}

console.log(55555555555);
console.log(typeof obj1);
console.log(typeof obj2);
if(obj1 == obj2){

console.log('55555555555');
}else{

console.log("666666666");
}

var obj2 = shallowCopy(obj1);
obj2.name = 1;
obj2.xxx[0] = 2;
console.log(obj1);
console.log(obj2);
obj1.xxx[2] = 2;

console.log(obj1);
console.log(obj2);

//深拷贝
function deepCopy(obj){
    var objArray = Array.isArray(obj) ? []: {};
    if(obj && typeof obj === "object"){
        for(var key in obj){
            if(obj.hasOwnProperty(key)){
                if(obj[key] && typeof obj[key] === "object"){
                    objArray[key] = deepCopy(obj[key]);
                }else{
                    objArray[key] = obj[key];
                }
            }
        }
    }
    return objArray;
}
var obj3 = deepCopy(obj1);
console.log(obj3);
console.log(obj1);
obj3.xxx[3] = 1111111;
console.log(obj3.xxx);
console.log(obj1.xxx);

//return 新数组 分配不同内存地址
function testarr(){
    return [1,[2,3]];
}


var a = testarr();
var b = testarr();
a[0] = 3;
a[1][0] = 3;
console.log(a);
console.log(b);

// retun 还是引用,共用地址
function newArr(obj){
    var newObj = obj;
    return newObj;

}
var c = [1,[2,3]]
var a = newArr(c);
var b =newArr(c);
c[0] = 666
a[1][1] =555;
console.log(a);
console.log(b);

你可能感兴趣的:(潜拷贝,深拷贝)