1 回答
TA贡献1890条经验 获得超9个赞
方法、函数都在下面,深复制/浅复制随便选,函数用 ES6 写的
var aa = 1,
bb = 2,
cc = 3,
dd = 4;
var a = { 'type': 1, list: [{ 'id': 1, 'name': aa }, { 'id': 2, 'name': bb }] };
var b = { 'type': 2, list: [{ 'id': 3, 'name': cc }, { 'id': 4, 'name': bb }] };
var c = [{ 'type': 1, list: [{ 'id': 1, 'name': aa }, { 'id': 2, 'name': bb }] }, { 'type': 2, list: [{ 'id': 3, 'name': cc }, { 'id': 4, 'name': bb }] }]
var resultDeep = [JSON.parse(JSON.stringify(a)), JSON.parse(JSON.stringify(b))];
var resultShallow = [a, b];
console.log(JSON.stringify(resultShallow) === JSON.stringify(c));//true
console.log(JSON.stringify(resultDeep) === JSON.stringify(c));//true
//函数提炼
function splicingObjects(deepOrShallow, ...obj) {
let result = [];
if (deepOrShallow === 'deep') {
obj.forEach((obj) => { result.push(JSON.parse(JSON.stringify(obj)));});
} else if (deepOrShallow === 'shallow') {
result = [...obj];
}
return result;
}
let resultDeep2 = splicingObjects('deep',a,b);
let resultShallow2=splicingObjects('shallow',a,b);
console.log(JSON.stringify(resultShallow2) === JSON.stringify(c));//true
console.log(JSON.stringify(resultDeep2) === JSON.stringify(c));//true
添加回答
举报
