递归函数返回值 undefined

getItem(obj, arr, index) {
    if (arr.length - 1 !== index) {
       const tempObj = obj[arr[index]];
       this.getItem(tempObj, arr, index + 1);
   }
   return obj[arr[index]];
},    

const obj = { foo: { bar: { name: 'biz' } } };
const path = 'foo.bar.name';
const childArr = path.split('.');
console.log('第一步', this.getItem(obj, childArr, 0));

最后一行 console.log 本来期望返回值应该是 ‘biz’,结果返回的却是 undefined;

查询原因后,发现忘记在递归时 return,导致递归的最深层一个函数调用时有值,但最外层的函数的返回值却是 undefined;

最后一次进行递归操作的时候值是返回了,但只返回到了递归自己调用的函数里,而最初的函数是没有返回值的·,所以打印出来就是undefined,如果想要函数最后一次计算所得值,就需要在每次调用该函数的时候进行return,每一次return都是把最新的函数调用返回到外层的函数调用,所以通过调用函数就能拿到值了。

getItem(obj, arr, index) {
    if (arr.length - 1 !== index) {
       const tempObj = obj[arr[index]];
       return this.getItem(tempObj, arr, index + 1);
   }
   return obj[arr[index]];
},    

const obj = { foo: { bar: { name: 'biz' } } };
const path = 'foo.bar.name';
const childArr = path.split('.');
console.log('第一步', this.getItem(obj, childArr, 0));
原文地址:https://www.cnblogs.com/momo798/p/11718639.html