关于深拷贝和浅拷贝的学习分享

时间:2022-09-02 19:51:13

今天看了一个关于深拷贝和浅拷贝的问题解释,挺好的,写出来分享一下

1.浅拷贝

var obj1 = {a:1,b:10};
var obj2 = obj1;

此时如果改变obj2的值的话,obj1的值也会跟着变

2.深拷贝

简单写法:

var obj3 = {a:1,b:10};
var obj4 = {a:obj3.a,b:obj3.b};

//在这里更改obj4的b不会影响obj3的值
obj4.b = 100;
console.log(obj3)
console.log(obj4)

封装函数写法:

function deepClone(initalObj, finalObj) {
  var obj = finalObj || {};
  for (var i in initalObj) {
    if(typeof initalObj[i] === 'object') {
      obj[i] = (initalObj[i].constructor === Array) ? [] : {};
      deepClone(initalObj[i], obj[i]);
    }else {
      obj[i] = initalObj[i];
    }
  }
  return obj;
}
var str = {};
var obj = { a: "hello", b: 21 };
deepClone(obj, str);
console.log(str.a);