[英]Need help creating simple javascript incremental function
我需要幫助以遞歸方式創建 function 並且我無法將我的頭腦圍繞我需要創建它的代碼。
這是我需要做的:
我有一個數字和一個數字數組
我想檢查該數字是否在數組中
如果是,我想將它加一,然后檢查這個現在的當前數字是否在數組中
如果是我想做同樣的事情
直到我到達不在數組中的下一個數字和 output 不在數組中的數字
const getNextAvailableIndex = () => {
let nextIdx = 0
let foundNext = false
if (nextDelivery?.indexFromScheduleStart) {
if (skippedIndxs.includes(nextDelivery?.indexFromScheduleStart)) {
nextIdx = nextDelivery?.indexFromScheduleStart
while (foundNext === false) {
nextIdx++
if (!skippedIndxs.includes(nextIdx)) {
foundNext = true
}
}
}
}
return nextIdx
}
編輯:我的代碼有效,但我知道我可以用更簡單的方式做到這一點。
你的代碼讓我很困惑。 我不確定您是否正在尋找像這個遞歸實現這樣簡單的東西:
const firstFree = (ns, start = 0) => ns.includes (start)? firstFree (ns, start + 1): start const ns = [18, 7, 12, 6, 15, 10, 5, 14, 4, 9, 16, 8, 20] console.log (firstFree (ns, 3)) //=> 3: 3 is not included console.log (firstFree (ns, 12)) //=> 13: 12 is included, but 13 is not console.log (firstFree (ns, 4)) //=> 11: 4, 5, 6, 7, 8, 9, & 10 are included, but 11 is not
在這里,我們的 function 測試目標 integer 是否在數組中。 如果是,我們使用下一個更高的 integer 重復。 如果不是,我們返回目標。
如果這不能回答問題,您能否添加一些示例並顯示預期結果?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.