我正在通过Eloquent JavaScript这本书。其中一个练习要求你创建一个列表中返回第n个值的递归功能,格式为:在JavaScript中从内部函数返回外部函数的问题
var list = {value: 10, rest: {value: 20, rest: {value: 30, rest: null}}};
我自认为和理解作者的解决方案(我现在意识到我其实没”牛逼需要内部函数),但我仍然好奇,为什么我的代码不工作:
function nth(list, num){
var count = 0;
function findNum(node){
if(count == num){
var result = node.value;
console.log("From inner function: " + result);
return result;
}else {
node = node.rest;
count++
findNum(node);
}
}
var output = "From outer function: " + findNum(list);
return output;
}
我已经研究了答案here,我似乎做正确的事返回从内部函数中,但是当调用外部函数时,我得到以下结果:
console.log(nth({value: 10, rest: {value: 20, rest: {value: 30, rest: null}}}, 0));
//From inner function: 10
//From outer function: 10
console.log(nth({value: 10, rest: {value: 20, rest: {value: 30, rest: null}}}, 1));
//From inner function: 20
//From outer function: undefined
console.log(nth({value: 10, rest: {value: 20, rest: {value: 30, rest: null}}}, 2));
//From inner function: 30
//From outer function: undefined
我的问题是:为什么在寻找第一个值时,外部函数返回了预期的结果,而在另外两种情况下返回'undefined'?
得到的是什么呀,我发现关于锻炼的几个答案,但我看不出一个解决这方面的问题 – CJ1138
没有什么,不能简单地走来解决通过调试器中的代码观察它的功能。 – 2017-01-16 12:06:02