javascript深拷贝和浅拷贝
- 0
#讨论区
00条评论
实时对话
loading...
js
...
运算符Array.prototype.concat()
Array.prototype.slice()
缺点:只适用JSON安全的对象
js
js
js
js
javascript
javascript
单独处理各个数据类型 funtion map set 等等
js
//todo
var _ = require('lodash');
var obj1 = { a: 1, b: { f: { g: 1 } }, c: [1, 2, 3]};
var obj2 = _.clone(obj1);console.log(obj1.b.f === obj2.b.f);// true
const test = { name: "test"};
const data = { a: "123",
b: 123,
c: true,
d: [43, 2],
e: undefined,
f: null,
g: function() { console.log("g"); },
h: new Set([3, 2, null]),
i: Symbol("fsd"),
j: test,
k: new Map([ ["name", "张三"], ["title", "Author"] ]),
l: NaN,
m: new RegExp(".*?"),
n: new Date()
};
console.log(JSON.parse(JSON.stringify(data)))
const _ = require('lodash');
const obj1 = { a: 1, b: { f: { g: 1 } }, c: [1, 2, 3]};
const obj2 = _.cloneDeep(obj1);console.log(obj1.b.f === obj2.b.f);
function deepClone(val) {
return new Promise(resolve => {
const { port1, port2 } = new MessageChannel()
port2.onmessage = e => resolve(e.data)
port1.postMessage(val)
})
}
function deepClone(target) {
let cloneTarget = {};
const keys=Object.keys(target)
for (const key of keys) {
cloneTarget[key] = target[key];
}
return cloneTarget;
};
function deepClone(target) {
if(typeof target==='object'){
let cloneTarget = Array.isArray(target) ? [] : {};
const keys = Object.keys(target)
for (const key of keys) {
cloneTarget[key] = deepClone(target[key]);
}
return cloneTarget;
}else {
return target
}
};
function deepClone(target,map = new Map()) {
if(typeof target==='object'){
let cloneTarget = Array.isArray(target) ? [] : {};
if (map.has(target)) {
return target;
}
map.set(target, cloneTarget);
const keys = Object.keys(target)
for (const key of keys) {
cloneTarget[key] = deepClone(target[key],map);
}
return cloneTarget;
}else {
return target
}
};
function deepClone(target, map = new WeakMap()) {
if (typeof target === 'object') {
if (target === null) {//null
return null
}
if(target instanceof Date){
return target
}
let cloneTarget = Array.isArray(target) ? [] : {};
if (map.has(target)) {
return target;
}
map.set(target, cloneTarget);
const keys = Object.keys(target)
for (const key of keys) {
cloneTarget[key] = deepClone(target[key], map);
}
return cloneTarget;
} else {
return target
}
}