首页 > 解决方案 > Javascript:链接对象/列表函数返回未定义

问题描述

我正在尝试返回链接对象(列表)的长度。但是,我编写的函数没有返回任何内容。

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'

标签: javascriptfunctionobjectscope

解决方案


您需要return递归调用:

return countDepth(liste, count);

另请注意,它可以进行优化并使其更简洁,如下所示:

const countDepth = (l, c = 0) => !l ? c : countDepth(l.rest, ++c);

推荐阅读