递归函数,在javascript中调用for循环内部的递归



我有一个街道的类,它只是一条有起点和终点的线,在这个类中,我有一种叫做checkIntersections的函数,它:

  • 检查该街道是否与给定的街道及其子街道相交,这些街道也是街道类型
  • 在第一个找到的交集处返回true
  • 如果未找到递归交集,则返回false或未定义

我决定将checkIntersections作为一个递归函数,但我认为我做得不对,因为街道之间的嵌套交叉口没有被检测到。

  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]);  
  }
}

}

在javascript中的for循环中进行递归调用时,有什么需要注意的吗?函数的输出总是未定义的。

您的代码没有使用递归调用返回的值——它只是忽略它,然后继续下一个递归调用。相反,它应该检测到递归调用的成功,然后立即退出,将该成功返回给自己的调用者。

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!
        }
    }
}

它应该是类似的东西

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;
}

  • 您需要returncheckIntersections的递归调用
  • 最好将.some用于children,因为它将提前退出
  • 如果没有子项并且当前交集失败,则需要提供默认返回

最新更新