【问题标题】:Javascript: Linked object/list function returning undefinedJavascript:链接对象/列表函数返回未定义
【发布时间】:2019-12-30 04:55:49
【问题描述】:

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

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'

【问题讨论】:

    标签: javascript function object scope


    【解决方案1】:

    你需要return递归调用:

    return countDepth(liste, count);
    

    另请注意,它可以像这样优化并变得更简洁:

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

    【讨论】:

    • 这行得通,但您可以解释原因以供将来参考?
    • 因为如果if语句没有被执行,那么在函数的执行中没有返回,所以undefined被返回。
    • 哦..我认为这是有道理的。第一次迭代返回第二次迭代,第二次迭代返回第三次,依此类推......一直到实际答案。如果没有第二个 return 语句,这条链就会被打破,而实际的答案将被放弃。
    猜你喜欢
    • 2019-05-12
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    相关资源
    最近更新 更多