xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

JS Object Deep Copy & 深拷贝 All In One

JS Object Deep Copy & 深拷贝 All In One

js data types

image

基本数据类型:(栈)

7种基本数据类型 Undefined、Null、Boolean、Number 和 String,Symbol, BigInt;
变量是直接按值存放的;
存放在栈内存中的简单数据段,可以直接访问;

引用数据类型:(堆)

Array, Object, Function, Date, Math, RegExp, ...

TypedArray: Uint8Array, Int8Array, ...
DataView, ArrayBuffer, ...

Map, Set, WeakMap, WeakSet, Intl, ...
Reflect, Proxy, ...

存放在堆内存中的对象,变量保存的是一个指针,这个指针指向另一个位置;
当需要访问引用类型(如对象,数组等)的值时,首先从栈中获得该对象的指针地址,
然后再从堆内存中取得所需的数据;

JavaScript 存储对象都是存的内存地址;

所以浅拷贝会导致 obj1 和obj2 指向同一块内存地址;
改变了其中一方的内容,都是在原来的内存上做修改会导致拷贝对象和源对象都发生改变;

深拷贝是开辟一块新的内存地址,将原对象的各个属性逐个复制进去, 对拷贝对象和源对象各自的操作互不影响;

const origin = {
  num: 1,
  arr: [2012, 2023],
  func: (v) => console.log(v),
  obj: {msg: 'bug'},
  date: new Date(`2012-01-01`),
  u: undefined,
  nil: null,
  nan: NaN,
  bool: true,
  str: 'string',
  s: Symbol(`s`),
  bi: BigInt(10**32),
  set: new Set([1, 2, 3]),
  map: new Map([['a', 11], ['b', 22], ['c', 33]]),
  // reg: /^0+/g,
  reg: new RegExp(/^0+/g),
};

image

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects

针对深度拷贝,需要使用其他方法 JSON.parse(JSON.stringify(obj));,因为 Object.assign() 拷贝的是属性

假如源对象的属性值是一个指向对象的引用,它也只拷贝那个引用

深拷贝

// 递归实现
"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2017-06-13
 * @modified 2023-02-20
 *
 * @description JS 对象深拷贝 & JS 对象浅拷贝 All In One
 * @description js object deepClone /js object shallowCopy
 * @difficulty Easy
 * @ime_complexity O(n)
 * @space_complexity O(n)
 * @augments
 * @example
 * @link https://www.cnblogs.com/xgqfrms/p/6942570.html
 * @link https://www.cnblogs.com/xgqfrms/p/7000492.html
 * @solutions
 *
 * @best_solutions
 *
 */

// export {};

const log = console.log;

// JS 对象深拷贝 / js object deepClone
function deepClone(obj) {
  if(typeof obj !== "object") {
    return obj;
  }
  if(Array.isArray(obj)) {
    return obj.map(i => deepClone(i));
  }
  let temp = {};
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      const item = obj[key];
      if(Array.isArray(item)) {
        temp[key] = item.map(i => deepClone(i));
      } else {
        temp[key] = deepClone(item);
      }
    }
  }
  return temp;
}



// 测试用例 test cases
const testCases = [
  {
    input: '{"k":1,"e":["a2",{"a3":"a3"}],"y":{"l2":2,"l3":{"key":3}}}',
    result: '{"k":1,"e":["a2",{"a3":"a3"}],"y":{"l2":2,"l3":{"key":2023}}}',
    desc: 'value equal to {"k":1,"e":["a2",{"a3":"a3"}],"y":{"l2":2,"l3":{"key":2023}}}',
  },
];

for (const [i, testCase] of testCases.entries()) {
  const obj = JSON.parse(testCase.input);
  const result = deepClone(obj);
  result.y.l3.key = 2023;
  log(`test case ${i} result: `, JSON.stringify(result) === testCase.result ? `✅ passed` : `❌ failed`, result);
  log(`test case ${i} result: `, JSON.stringify(obj) === testCase.input ? `✅ passed` : `❌ failed`, obj);
}

/*
$  npx ts-node ./deepClone.ts

test case 0 result:  ✅ passed { k: 1, e: [ 'a2', { a3: 'a3' } ], y: { l2: 2, l3: { key: 2023 } } }
test case 0 result:  ✅ passed { k: 1, e: [ 'a2', { a3: 'a3' } ], y: { l2: 2, l3: { key: 3 } } }

*/



/*

const obj = {k: 1, e: ['a2', {a3: 'a3'}], y: {l2: 2, l3: {key: 3}}};

const temp = deepClone(obj);
// console.log(`temp =`, temp);

temp.y.l3.key = 2023;

console.log(`temp.y.l3.key =`, temp.y.l3.key);
console.log(`temp =`, temp);

console.log(`\n`);

console.log(`obj.y.l3.key =`, obj.y.l3.key);
console.log(`obj =`, obj);


$ npx ts-node ./deepClone.ts

// temp.y.l3.key = 2023
// temp = { k: 1, e: [ 'a2', { a3: 'a3' } ], y: { l2: 2, l3: { key: 2023 } } }

// obj.y.l3.key = 3
// obj = { k: 1, e: [ 'a2', { a3: 'a3' } ], y: { l2: 2, l3: { key: 3 } } }

*/

image

// JSON.parse & JSON.stringify

const newObj  = JSON.parse(JSON.stringify(obj));

image

// 结构化克隆 structuredClone

浅拷贝

Object.assign

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign


function test() {
  let a = { b: {c:4} , d: { e: {f:1}} };

  let g = Object.assign({},a);

  let h = JSON.parse(JSON.stringify(a));

  console.log(g.d); // { e: { f: 1 } }
  g.d.e = 32;

  console.log('g.d.e set to 32.') 
// g.d.e set to 32.
  console.log(g); // { b: { c: 4 }, d: { e: 32 } }
  console.log(a); // { b: { c: 4 }, d: { e: 32 } }

  console.log(h);
// { b: { c: 4 }, d: { e: { f: 1 } } }


  h.d.e = 54;
  console.log('h.d.e set to 54.') ;
// h.d.e set to 54.

  console.log(g); // { b: { c: 4 }, d: { e: 32 } }
  console.log(a); // { b: { c: 4 }, d: { e: 32 } }

  console.log(h); 
// { b: { c: 4 }, d: { e: 54 } }
}
test();


(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://www.zhihu.com/column/p/27242519

https://zhuanlan.zhihu.com/p/27242519



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2017-06-13 12:33  xgqfrms  阅读(173)  评论(2编辑  收藏  举报