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));