对象中存在环描述:
let obj = {
name:"mochen",
age:18,
};
obj.xinzeng = obj;
上面的obj对象中就存在环,在浏览器中输出,它的xinzeng属性会一直递归下去。利用JSON.stringtify(obj)报错(Converting circular structure to JSON),
实现一个函数,判断输入的对象中是否存在环:
function isCycle(obj) {
let is_Cycle = false;
let value = [];
let keys = Object.keys(obj);
(function (tobj) {
keys.forEach(val => {
let temp = obj[val];
if (typeof temp == "object" && temp != null) {
if (value.indexOf(temp) != -1) {
is_Cycle = true;
return;
} else {
value.push(temp);
arguments.callee(temp);
}
}
})
}
)(obj);
return is_Cycle;
}
网友评论