Javascript 在未知深度对象上循环时出现问题

Javascript 在未知深度对象上循环时出现问题,javascript,Javascript,我正在用投票排序来处理评论线程。我有一个基本对象,看起来像这样 { "user_name": "string", "comment": "string", "points": "integer", "date_time": "dateObject", "avatar_pic": "URL", "profile_link": "URL" } for each iteration of loop over comments array call someFunction someFunction

我正在用投票排序来处理评论线程。我有一个基本对象,看起来像这样

{
"user_name": "string",
"comment": "string",
"points": "integer",
"date_time": "dateObject",
"avatar_pic": "URL",
"profile_link": "URL"
}
for each iteration of loop over comments array call someFunction

someFunction(){
for by points
write properties of object to screen
check if child property has an array.  If array call someFunction on that array.
}
现在你可以忽略一切都是字符串的事实。只是为了测试

这是带有多个注释的较大对象。将有一个未知的嵌套深度

{
"comments": [
    {
        "user_name": "string",
        "comment": "string",
        "points": "integer",
        "date_time": "dateObject",
        "child": [
            {
                "user_name": "string",
                "comment": "string",
                "points": "integer",
                "date_time": "dateObject",
                "child" : null,
            }
        ]
    },
    {
        "user_name": "string",
        "comment": "string",
        "points": "integer",
        "date_time": "dateObject",
        "child": null
    }
]
}

我现在在psudo代码中的工作原理是这样的

{
"user_name": "string",
"comment": "string",
"points": "integer",
"date_time": "dateObject",
"avatar_pic": "URL",
"profile_link": "URL"
}
for each iteration of loop over comments array call someFunction

someFunction(){
for by points
write properties of object to screen
check if child property has an array.  If array call someFunction on that array.
}
基本上for循环会自动检查嵌套。然后,如果它在那里,则继续向下循环,并在屏幕上按逻辑顺序构建注释。我试图记住的另一个要求是嵌套深度。我想根据嵌套级别缩进注释。如果最大缩进为3或4,则它们将直接向下,而不是在页面上进一步缩进


较大的格式是完全灵活的。如果有更好的数据结构可供使用,我完全赞成。我希望这是有意义的,你们摇滚

IMO如果需要嵌套注释,那么结构是好的。如果你没有,拥有它不会消耗太多资源。我建议在打印到html时保存每个注释深度,然后您可以根据需要设置样式

function process (obj, func) {
    func(obj);
    if (obj.child) {
        obj.child.forEach(function (child) {
            process(child, func);
        });
    }
}
用法:

process(yourObj, function (obj) {
    // e.g.
    cosnole.log(obj.user_name);
});

如果我正确理解您要做的事情,您的伪代码将如下所示:

someFunction(){
if child property has an array -> call someFunction()  

else child property has null -> process, and then set this very child to null, and call someFunction again
}

为了更好地监督这些类型的对象遍历,您应该查看和使用一种特殊的方式来遍历它们,这与您想要做的事情非常接近

您是专门询问缩进还是递归函数调用?看起来你很清楚该怎么做,所以我不清楚你在问什么。Yhea我想这是在跟踪缩进和递归函数调用。缩进可以通过简单地传递一个数字作为参数来跟踪。您可以使用该数字的倍数来创建缩进字符串。当进行递归调用时,会传递一个递增的数字值。你可以把它限制在你想要的最大值。我想你已经掌握了递归函数的工作原理。太棒了!!谢谢,我不知道为什么我在这件事上遇到麻烦。我知道我很接近:)@Call\u Back\u函数是的,如果你愿意,你可以投票;)