在其他情况下如何忽略循环

时间:2019-08-29 21:17:11

标签: javascript angularjs

我必须比较两个值。这两个值来自不同的循环。 如果该值是精确匹配,则我以不同的方式推送数组。

您可以在代码中看到。我不能在“ if”函数后使用“ else”,因为它会识字直到循环停止。我会多次按下。

如果我在循环后添加array.push,将有2次推送。


for (var prop in obj) {
    var array = []
    for (var item in obj[prop]) {
        for (var i = 0; i < doctyp88.length; i += 1) {

            var doctyp88ID = doctyp88[i]._id;
            var doctyp88name = doctyp88[i]._source['88_name'];

            if (item == doctyp88ID) {
                array.push({
                    "name": item,
                    "count": obj[prop][item],
                    "archivname": doctyp88name,
                });
            }
        }

        array.push({
            "name": item,
            "count": obj[prop][item],

        });
    }
}

避免我的问题的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

for (var prop in obj) {
    var array = []
    for (var item in obj[prop]) {
        const newObj = {
               "name": item,
         } 
        for (var i = 0; i < doctyp88.length; i += 1) {

            var doctyp88ID = doctyp88[i]._id;
            var doctyp88name = doctyp88[i]._source['88_name'];

            newObj.count= obj[prop][item],


            if (item == doctyp88ID) {
                newObj.archivname = doctyp88name
            }
        }

        array.push(newObj);
    }
}

答案 1 :(得分:0)

如果我正确理解了您的问题,则可以使用break [label];语句退出嵌套循环并跳过更多的推送操作,但不要这样退出for之外:

loop_1:
for (var prop in obj) {
    var array = []

    loop_2:
    for (var item in obj[prop]) {

        loop_3:
        for (var i = 0; i < doctyp88.length; i += 1) {

            var doctyp88ID = doctyp88[i]._id;
            var doctyp88name = doctyp88[i]._source['88_name'];

            if (item == doctyp88ID) {
                array.push({
                    "name": item,
                    "count": obj[prop][item],
                    "archivname": doctyp88name,
                });
                break loop_2;
            }
        }

        array.push({
            "name": item,
            "count": obj[prop][item],

        });
    }
}