JS 对象深拷贝 & JS 对象浅拷贝 All In One
JS 对象深拷贝 & JS 对象浅拷贝 All In One
deepClone / shallowCopy
js data types
基本
值
数据类型:(栈)
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),
};
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
针对深度拷贝,需要使用其他方法 JSON.parse(JSON.stringify(obj));
,因为 Object.assign()
拷贝的是属性值。
假如源对象的属性值是一个指向对象的引用,它也只拷贝那个引用值。
JS Object Deep Copy
/ Deep Clone
// 递归实现
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2017-06-04
* @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 } } }
*/
// JSON.parse & JSON.stringify
const newObj = JSON.parse(JSON.stringify(obj));
// structuredClone 结构化克隆
JS Object Shallow Copy
/ Shallow Clone
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Array.from
浅拷贝
function recursiveClone(obj) {
return Array.isArray(obj) ? Array.from(obj, recursiveClone) : obj;
}
const obj = {k: 1, e: {y: 2}};
{k: 1, e: {…}}
const dc = recursiveClone(obj);
{k: 1, e: {…}}
dc.e.y = 3;
// 3
obj.e.y;
// 3
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
https://github.com/wengjq/Blog/issues/3#issuecomment-526222012
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();
jQuery
I want to note that the .clone() method in jQuery only clones DOM elements.
https://api.jquery.com/jQuery.extend/
将两个或多个对象的内容合并到第一个对象中。
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
https://api.jquery.com/jquery.extend/
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/6942570.html
未经授权禁止转载,违者必究!