为什么我的浅拷贝能实现深拷贝的效果?
如图,改变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);
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
shallowClone(obj1);这个方法获取的obj是跟obj1没关系的东西,如果obj2=obj1,这样就有关系了
我懂了,是我检验的方式出现了问题。修改的不应该是变量的引用,而是引用的那个对象中的属性值