简体   繁体   English

无法嵌套forEach可以在Javascript中使用

[英]can't get nested forEach to work in Javascript

So I guess the title is selfexplanatory. 所以我想标题是不言而喻的。 I have some code with nested forEach loops inside it. 我有一些内部嵌套forEach循环的代码。 The loops are iterating over an array of chapter objects. 循环正在遍历chapter对象的数组。 Each object can have multiple child nodes and they again can have multiple child nodes, and so on. 每个对象可以具有多个子节点,并且它们又可以具有多个子节点,依此类推。

I want to end up with one array which contains nested arrays with the child nodes. 我想结束一个数组,其中包含带有子节点的嵌套数组。

So far my code looks like this: 到目前为止,我的代码如下所示:

exports.chapter = function(req, res) {
    var chapters = [],
        result = [];

    chapters = exports.index(req, res);

    chapters.forEach(function(chapter) {
        if(chapter.orphan){
            result.add({
                'chapter': chapter,
                'children': getChildren(chapter.children)
            });
        }
    });

    function getChildren(siblings) {
        var children = [];

        chapters.forEach(function(chapter) {
            if($.inArray(chapter, siblings)){
                children.add({
                    'chapter': chapter,
                    'children': getChildren(chapter.children)
                });
            }
        });

        return children;
    };
};

I don't get any errors except for my page not loading. 除了页面未加载外,我没有任何错误。 It doesn't write anything in my console. 它在我的控制台中什么也没写。 I think it's a problem in the setup but I'm unable to find out where at the moment. 我认为这是安装程序中的问题,但目前无法确定位置。 Really hope you guys can help. 真的希望你们能提供帮助。

Most likely problem is here: 最可能的问题在这里:

if($.inArray(chapter, siblings)){

$.inArray is a horribly misnamed method: It returns an index , or -1 if not found, not a flag as the name implies. $.inArray是一个可怕的错误命名方法:它返回一个index ,如果找不到则返回-1,顾名思义,它不是标志。 -1 is, of course, truthy; -1当然是真实的; and 0 (a valid index), is falsey, so your if probably wants to be 0 (有效索引)为假,因此, if您想成为

if($.inArray(chapter, siblings) != -1){
    // We found it...
}

or possibly 或可能

if($.inArray(chapter, siblings) == -1){
    // We didn't find it
}

It's a bit strange.. I don't understand why you're using 'add' instead of 'push' method. 有点奇怪。我不明白为什么您要使用“添加”而不是“推送”方法。 If I try to "add" an object to an array I get an usual error. 如果尝试将对象“添加”到数组中,则会出现通常的错误。 Don't you? 是不是

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM