深拷贝
解决对象数组无限嵌套
function deepClone(x) {
const root = {};
// 栈
const loopList = [
{
parent: root,
key: undefined,
data: x
}
];
while (loopList.length) {
// 深度优先
const node = loopList.pop();
const parent = node.parent;
const key = node.key;
const data = node.data;
// 初始化赋值目标,key为undefined则拷贝到父元素,否则拷贝到子元素
let res = parent;
if (typeof key !== "undefined") {
res = parent[key] = {};
}
for (let k in data) {
if (Object.prototype.hasOwnProperty.call(data, k)) {
if (typeof data[k] === "object") {
if (Array.isArray(data[k])) {
res[k] = [].concat(JSON.parse(JSON.stringify(data[k])));
} else {
// 下一次循环
loopList.push({
parent: res,
key: k,
data: data[k]
});
}
} else {
res[k] = data[k];
}
}
}
}
return root;
}