【发布时间】:2021-07-15 04:15:24
【问题描述】:
本练习的最后一部分是编写一个递归函数,它接受两个参数,分别是连接列表和索引。该函数将在列表中的相应索引处查找对象中的值。我编写的代码按我想要的方式工作(我可以看到它在每次调用该函数时都在 console.log 中工作。但在最后一次它引用 undefined 作为我的值。我不明白为什么。哦,它有效索引为 0。代码如下。
首先,列表如下所示:
list = {
value: 1,
rest: {
value: 2,
rest: {
value: 3,
rest: null
}
}
};
const nth = (list, targetNum) => {
let value = Object.values(list)[0];
if (targetNum == 0) {
return value;
} else {
targetNum = targetNum -1;
list = Object.values(list)[1];
// console.log(value);
// console.log(targetNum);
// console.log(list);
nth(list, targetNum);
}
};
console.log(nth(arrayToList([1,2,3]),2));
下面是 arrayToList 的代码,它是练习的第一部分,如果你有任何很酷的 cmets,导致提示最终建议从最后构建列表。
const arrayToList = (arr) => {
let list = {
value: arr[0],
rest: nestObject()
};
function nestObject() {
let rest = {};
arr.shift();
const length = arr.length;
if (length == 1) {
rest.value = arr[0];
rest.rest = null;
} else {
rest.value = arr[0];
rest.rest = nestObject();
}
return rest;
}
return list;
};
【问题讨论】:
标签: javascript arrays list object