[英]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 :
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; }
return
the recursive call to checkIntersections
return
对checkIntersections
的递归调用.some
for the children
as it will do a early exitchildren
使用.some
会更好,因为它会提前退出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.