阅读 104

js 对象浅拷贝和深拷贝

浅拷贝

直接赋值

const obj = {name: 'zjx'};
const obj2 = obj;
obj.name = 'zjx2';
console.log(obj); // {name: 'zjx2'}
console.log(obj2); // {name: 'zjx2'}
复制代码

深拷贝

循环遍历

function copyObj(obj) {
  let newObj = {};
  for (var key in obj) {
    newObj[key] = obj[key];
  }
  return newObj;
}
const obj = {name: 'zjx'};
const obj2 = copyObj(obj);
obj.name = 'zjx2';
console.log(obj); // {name: 'zjx2'}
console.log(obj2); // {name: 'zjx'}
复制代码

通过 JSON.stringify 和 JSON.parse

此种方式,对象内的函数不会被拷贝,会造成函数丢失现象。

const obj = {name: 'zjx', test: function () {console.log('0')}};
const obj2 = JSON.parse(JSON.stringify(obj));
obj.name='zjx2';
console.log(obj); // {name: 'zjx2', test: function () {console.log('0')}}
console.log(obj2); // {name: 'zjx'}
obj2.test(); // obj2.test is not a function
复制代码

ES6 扩展运算符

const obj = {name: 'zjx'};
const obj2 = {...obj};
obj.name = 'zjx2';
console.log(obj); // {name: 'zjx2'}
console.log(obj2); // {name: 'zjx'}
复制代码
文章分类
阅读
文章标签