美文网首页程序员
javascript中检查对象是否存在环

javascript中检查对象是否存在环

作者: 信仰与初衷 | 来源:发表于2018-04-24 16:07 被阅读0次

JavaScript中,为了保证代码健壮性,我们需要确认对象中不存在环,现在有2种方法检测js对象是否有环

  • 方法一
function cycleDetector (obj) {
    console.log(arguments)
  // 请添加代码
    let result = false;
    try {
        JSON.stringify(obj);
    } catch (e) {
        result = true;
    } finally {
        return result;
    }
}
  • 方法二
function cycleDetector2(obj) {
    let hasCircle = false,
        cache = [];

    (function(obj) {
        Object.keys(obj).forEach(key => {
            const value = obj[key]
            if (typeof value == 'object' && value !== null) {
                const index = cache.indexOf(value)
                if (index !== -1) {
                    hasCircle = true
                    return
                } else {
                    cache.push(value)
                    arguments.callee(value)
                    // (注:箭头函数没有arguments对象,此时的arguments指向该匿名函数的参数)
                }
            }
        })
    })(obj)

    return hasCircle
}

运行代码

const obj = {
  foo: {
    name: 'foo',
    bar: {
      name: 'bar',
      baz: {
        name: 'baz',
        aChild: null  //待会让它指向obj.foo
      }
    }
  }
}

obj.foo.bar.baz.aChild = obj.foo
var currentTime = new Date().getTime()
var flag = cycleDetector(obj)
var endTime = new Date().getTime()
var time = endTime - currentTime
console.error(flag, time)

var currentTime2 = new Date().getTime()
var flag2 = cycleDetector2(obj)
var endTime2 = new Date().getTime()
var time2 = endTime2 - currentTime2
console.error(flag2, time2)

返回结果

{ '0': { foo: { name: 'foo', bar: [Object] } } }
true 5
true 0

第一种才用try catch的捕获异常的方法来判断,需要的时间更长,代码更简洁。
第二种方法时间更快,但是它执行递归,逻辑较第一种更复杂,空间也需要更大。

相关文章

网友评论

    本文标题:javascript中检查对象是否存在环

    本文链接:https://www.haomeiwen.com/subject/lhyjlftx.html