如何检查物体的深度? [英] How to check the depth of an object?

查看:148
本文介绍了如何检查物体的深度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个具有可变深度的权限系统;根据页面的复杂程度,可能会有更多或更少的级别。我搜索了StackOverflow,发现之前是否有人问过,找不到它。

I'm working on a permissions system with variable depth; depending on the complexity of a page, there could be more or less levels. I searched StackOverflow to find if this has been asked before, couldn't find it.

如果我有这个对象:

{foo:{bar:{baz : 'baa'}}}

我需要它返回3,它有3个级别。

I need it to return 3, it has 3 levels to it.

使用此对象:

{abc: 'xyz'} 

它必须是1.

这是我到目前为止:

utils.depthOf = function(object, level){
    // Returns an int of the deepest level of an object
    level = level || 1;

    var key;
    for(key in object){
        if (!object.hasOwnProperty(key)) continue;

        if(typeof object[key] == 'object'){
            level++;
            level = utils.depthOf(object[key], level);
        }
    }

    return level;
}

问题在于它也计算姐妹元素。它实际上没有得到深度,它正在计算一个对象的所有成员。

The problem is it counts sister elements too. It's actually not getting depth, it's counting all members of an object.

推荐答案

好吧,在这里,你去找好友,这个功能完全符合你的需要!

Well, here you go buddy, a function that does exactly what you need!

utils.depthOf = function(object) {
    var level = 1;
    var key;
    for(key in object) {
        if (!object.hasOwnProperty(key)) continue;

        if(typeof object[key] == 'object'){
            var depth = utils.depthOf(object[key]) + 1;
            level = Math.max(depth, level);
        }
    }
    return level;
}

比我们想象的要容易得多。问题是它是如何递增的,它不应该是递归地添加,而是获得最底层并添加一个,然后选择两个兄弟之间的最大值。

A lot easier than we thought it would be. The issue was how it was incremented, it shouldn't have been recursively adding, rather getting the bottom-most and adding one, then choosing the max between two siblings.

这篇关于如何检查物体的深度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆