简体   繁体   English

递归 function 在 javascript 中的 for 循环内调用递归

[英]recursive function that calls recursion inside for loop in javascript

I have a class for a Street which is just a line with a beginning point and an end point, inside this same class I have a function called checkIntersections which:我有一条街道的 class ,它只是一条具有起点和终点的线,在同一个 class 内我有一个名为 checkIntersections 的 function :

  • checks if this Street intersects with a given Street and its children which are also of type Street.检查这条 Street 是否与给定的 Street 及其也是 Street 类型的子节点相交。
  • returns true at the first found intersection在第一个找到的交点处返回 true
  • returns false or undefined if no recursive intersections were found如果没有找到递归交集,则返回 false 或 undefined

I decided to make checkIntersections a recursive function but I think I'm going about it wrong because nested intersections between streets are not being detected.我决定将 checkIntersections 设为递归 function 但我认为我做错了,因为没有检测到街道之间的嵌套交叉点。

  checkIntersections(street){

if(intersects(this.beginning, this.end, street.beginning, street.end)){
  return true;
}
else{
  for(var i = 0 , count = street.children.length ; i < count ; i++){
    this.checkIntersections(street.children[i]);  
  }
}

} }

Is there anything that I should be attentive to while making recursive calls inside a for loop in javascript?在 javascript 的 for 循环中进行递归调用时,我应该注意什么? The output of the function is always undefined. function 的 output 始终未定义。

Your code is not using the value returned from the recursive call -- it just ignores it and just continues with the next recursive call.您的代码没有使用从递归调用返回的值——它只是忽略它并继续下一个递归调用。 Instead it should detect a success from a recursive call and then exit immediately, returning that success to its own caller.相反,它应该从递归调用中检测到成功,然后立即退出,将该成功返回给它自己的调用者。

checkIntersections(street) {
    if (intersects(this.beginning, this.end, street.beginning, street.end)) {
        return true;
    } else {
        for (let child of street.children) { // Use modern for..of loop
            let success = this.checkIntersections(child);
            if (success) return true; // bubble up the happy result!
        }
    }
}

It should be something like它应该是这样的

 checkIntersections(street) { if (intersects(this.beginning, this.end, street.beginning, street.end)) { return true; } else if (street.children.length) { return street.children.some( checkIntersections ); } return false; }

  • you need to return the recursive call to checkIntersections您需要returncheckIntersections的递归调用
  • it would be better to use .some for the children as it will do a early exitchildren使用.some会更好,因为它会提前退出
  • you need to provide a default return in case there are no children and the current intersection failed.如果没有子节点并且当前交集失败,则需要提供默认返回。

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

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