zoukankan      html  css  js  c++  java
  • 递归函数返回值 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));
  • 相关阅读:
    HDU 4296 Buildings(贪心)
    HDU 4288 Coder(线段树)
    hdu 5073 Galaxy
    ZOJ 3905 Cake(贪心+dp)
    ZOJ 3903 Ant(公式推导)
    除法求逆元(扩展欧几里德和费马小定理)
    HDU 4442 Physical Examination(关于贪心排序)
    ACM vim配置
    2015 南阳ccpc The Battle of Chibi (uestc 1217)
    次小生成树(入门)
  • 原文地址:https://www.cnblogs.com/momo798/p/11718639.html
Copyright © 2011-2022 走看看