Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

为什么我的浅拷贝实现了深拷贝的效果?

改变obj2的k2和k3属性,为什么obj1完全不受影响?

function shallowClone(obj){
    let newObj = {};
    for(const key in obj){
        newObj[key] = obj[key];
    }
    return newObj;
}

let obj1 = {
    k1:123,
    k2:{name:'k2'},
    k3:[1,2,[3,4]]
};
let obj2 = shallowClone(obj1);
obj2.k2 = {};
obj2.k3 = [1,2,3,4];
console.log(obj1);
console.log(obj2);

image


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

两个概念:

  • 浅拷贝深拷贝都是针对引用类型,浅拷贝是只复制了这份引用,导致对拷贝后的值作出的修改,也会影响原对象
  • 对象的赋值操作(eg: obj2.k2 = {}),实际上改变了变量的引用

所以,你对深浅拷贝的检验方式本质上是有问题的:

let obj2 = shallowClone(obj1);
obj2.k2.name = 'gaarahan';
obj2.k3.push(5);

这个才是正确的检验方式


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...