[英]Javascript: Linked object/list function returning undefined
我正在嘗試返回鏈接對象(列表)的長度。 但是,我編寫的函數沒有返回任何內容。
let linkedObject = { value: 1, rest: { value: 2, rest: { value: 3, rest: null } } }
function countDepth(liste, count = 0){
if (liste == null) return count
else {
count ++
liste = liste.rest
countDepth(liste, count)
}
}
console.log(countDepth(linkedObject))```
expected output:
'3'
actual output:
'undefined'
您需要return
遞歸調用:
return countDepth(liste, count);
還請注意,可以像這樣優化和簡化它:
const countDepth = (l, c = 0) => !l ? c : countDepth(l.rest, ++c);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.