javascript - 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'
解决方案
您需要return
递归调用:
return countDepth(liste, count);
另请注意,它可以进行优化并使其更简洁,如下所示:
const countDepth = (l, c = 0) => !l ? c : countDepth(l.rest, ++c);
推荐阅读
- python - 任何人都可以在机器人框架中帮助我,如何禁用麦克风和摄像头访问或在弹出窗口打开时单击允许?
- python-3.x - 使用 OpenCV 为 png 设置白色背景而不是透明度
- xpages - 在 xpage 上寻找签名按钮的最佳方法
- oracle-sqldeveloper - 在oracle sql developer中将值与VARCHAR2进行比较
- javascript - ECONNREFUSED 用于从本地主机到另一个本地主机的代理请求
- android - Android studio / IntelliJ 构建窗口自动显示
- javascript - Leaflet - 如何使用弹出表单中的数据创建标记
- gatsby - netlify cms gatsby 获取“必须设置标识符字段”以进行收集
- resize - gnome 键绑定三分之一窗口大小
- html - 如何使用 Angular 5 和引导程序放置 x 按钮以清除输入字段中的内容