循环引用有人说就是一种不健康的状态,即你中有我,我中有你
hasObj: any = [];
deepCopy(data: any) {
this.hasObj.push(data);
//最终就是返回数组或者对象
let t = this.type(data),
o: any,
i,
ni;
if (t === "array") {
o = []; //初始化
} else if (t === "object") {
o = {}; //初始化
} else {
return data;
}
if (t === "array") {
//console.log("t:%o,data:%o", t, data);
for (i = 0, ni = data.length; i < ni; i++) {
// if (data[i] == undefined) {
// break;
// }
o.push(this.deepCopy(data[i]));
}
return o;
} else if (t === "object") {
//console.log("t:%o,data:%o", t, data);
for (i in data) {
let index = this.hasObj.indexOf(data[i]);
if (index > -1) {
console.log("存在循环引用或属性引用了相同对象");
// 如果已存在,证明引用了相同对象,那么无论是循环引用还是重复引用,我们返回引用就可以了
o[i] = this.hasObj[index];
} else {
o[i] = this.deepCopy(data[i]);
}
}
return o;
}
}