【发布时间】:2018-03-29 08:38:56
【问题描述】:
所以我有以下函数将数组转换为列表并且工作正常:
function arrayToList (arr) {
var list = null
arr.reverse()
for (var i = 0; i < arr.length; i++) {
list = {value: arr[i], rest: list}
}
return list
}
现在我正在尝试编写一个返回列表第 n 个值的函数
function nth (list, number) {
if (number !== 0) {
nth(list.rest, number - 1)
} else {
console.log(typeof list.value)
return list.value
}
}
如果我运行 nth(list, 0) 它工作正常,但是当我在函数 console.log 中将索引(数字)更改为其他值(例如 1、2 等)时,显示 list.value 的类型是数字,但它返回的是未定义的 P.S:我正在使用 node.js 6.11.4 版来运行我的代码
【问题讨论】:
-
这是因为您将
list.rest传递给函数nth(list.rest, number - 1)。它没有.value。你可能想通过nth(list, number - 1)。 -
list.rest 包含另一个列表,如果你打印 list.value 它也会显示值
-
啊,是的,我错过了。你不会递归返回。请参阅下面的答案。
标签: javascript node.js list numbers undefined