遞歸函數返回值 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));

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM