我有一個 Street 類,它只是一條帶有起點和終點的線,在同一個類中,我有一個名為 checkIntersections 的函式,它:
- 檢查此 Street 是否與給定的 Street 及其同樣屬于 Street 型別的子項相交。
- 在第一個找到的交點處回傳真
- 如果沒有找到遞回交叉點,則回傳 false 或 undefined
我決定讓 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 回圈內進行遞回呼叫時,有什么我應該注意的嗎?函式的輸出總是未定義的。
uj5u.com熱心網友回復:
您的代碼沒有使用從遞回呼叫回傳的值——它只是忽略它并繼續下一個遞回呼叫。相反,它應該從遞回呼叫中檢測到成功,然后立即退出,將成功回傳給它自己的呼叫者。
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!
}
}
}
uj5u.com熱心網友回復:
它應該是這樣的
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遞回呼叫checkIntersections - 最好使用
.someforchildren因為它會提前退出 - 如果沒有孩子并且當前交叉點失敗,您需要提供默認回傳值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/403064.html
標籤:
下一篇:Lua遞回問題出乎意料的結果
