繁体   English   中英

在循环内调用函数会破坏它

[英]Calling a function inside a loop breaks it

我有一个函数,可以从MongoDB集合中循环一个对象。 这是一些邮件运输帖子的所有可能连接。 一旦获得一个连接,我想立即从连接对象中删除反向连接,例如postA = 1和postB = 2,我想删除postA = 2和postB = 1( removeConnection函数可以做到这一点)。

我不明白为什么当我尝试在calculateRoute运行该函数时,它只在控制台上返回一个“ A”,而在删除它时却返回三个“ A”(应该是它)。 该功能以某种方式打破了循环。

calculatedRoutes = calculateRoute(store.postid, client.postid, connections, []);

function calculateRoute(actualPost, finalPost, connections, routes) {
    for(i=0; i < connections.length; i++) {
        if(actualPost == connections[i].postA) {

            console.log('A');

            // If I remove this, the console shows A three times. If I keep this, only shows 1 time.
            connections = removeConnection(connections[i].postB, connections[i].postA, connections);
        }
    }

    return routes;
}

function removeConnection(postA, postB, connections) {
    for(i=0; i < connections.length; i++) {
        if(connections[i].postA == postA && connections[i].postB == postB) {
            delete connections[i];
            //break;
        }
    }

    return connections;
}

当您调用removeConnection时,似乎正在修改要迭代的集合。 我敢说在第一个循环之后, connections.length小于您的循环控制变量,这将导致循环终止。 函数调用后的connections内容是什么?

通常,直接修改要迭代的集合是不好的做法。 更好的选择是将集合投影到一个包含所需值的新集合中(使用map,filter等)。 这样,您就不会变异任何东西。

通过添加固定它vari=0上的每个for 有人可以解释吗?

for(var i=0; i < connections.length; i++) {...

暂无
暂无

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

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