Skip to content

Instantly share code, notes, and snippets.

@mactive
Created August 10, 2018 07:18
Show Gist options
  • Save mactive/7734555cdd720d523f1b045569042892 to your computer and use it in GitHub Desktop.
Save mactive/7734555cdd720d523f1b045569042892 to your computer and use it in GitHub Desktop.
JS 深度拷贝
let existed = [];
function deepcopy(d) {
let result = Array.isArray(d) ? [] : {};
const keys = Object.keys(d);
if(keys && keys.length > 0) {
keys.forEach( key => {
result[key] = deepcopy(d[key]);
})
} else {
console.log(d)
result = d;
}
return result;
}
JSPatch
let a = {};
let b = {};
a.b = b;
b.a = a;
console.log(a);
let aa = deepcopy(a);
console.log(aa);
/*
let a = {a:1, b:{c:2, d:3, e:[4, 5, {f:6}, [7, 8]]}};
let aa = deepcopy(a);
let b = aa['b'];
b['d'] = 10;
let e = b['e'];
e[0] = 100;
e[2]['f'] = 101;
e[3][0] = 102;
console.log(JSON.stringify(aa));
console.log(JSON.stringify(a));
*/
/*
function removeSub(main, sub) {
let ids = [];
main.forEach( (item, index) => {
if(sub.indexOf(item) > -1) {
ids.push(index);
}
})
ids.forEach(id => {
main.splice(id, 1)
})
}
let main = [1, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6];
let sub = [2, 4]
removeSub(main, sub);
console.log(main); //1, 3, 5, 6
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment