0
点赞
收藏
分享

微信扫一扫

js的深拷贝和浅拷贝的区别

以下是一个使用JavaScript实现深拷贝和浅拷贝的示例:

// 浅拷贝
function shallowCopy(obj) {
  if (typeof obj !== 'object' || obj === null) {
    return obj;
  }
  
  let copy = Array.isArray(obj) ? [] : {};
  
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      copy[key] = obj[key];
    }
  }
  
  return copy;
}

// 深拷贝
function deepCopy(obj) {
  if (typeof obj !== 'object' || obj === null) {
    return obj;
  }
  
  let copy = Array.isArray(obj) ? [] : {};
  
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      copy[key] = deepCopy(obj[key]);
    }
  }
  
  return copy;
}

// 示例
let obj1 = {
  name: 'John',
  age: 30,
  hobbies: ['reading', 'running']
};

let obj2 = shallowCopy(obj1);
let obj3 = deepCopy(obj1);

obj1.name = 'Jane';
obj1.hobbies.push('swimming');

console.log(obj2); // { name: 'John', age: 30, hobbies: [ 'reading', 'running', 'swimming' ] }
console.log(obj3); // { name: 'John', age: 30, hobbies: [ 'reading', 'running' ] }

在上面的示例中,shallowCopy函数实现了浅拷贝,它只复制对象的第一层属性,如果属性值是对象或数组,只复制引用。deepCopy函数实现了深拷贝,它递归地复制所有嵌套的对象和数组,确保每个属性都是一个新的副本。

举报

相关推荐

0 条评论