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));
  • 相关阅读:
    JavaScript Json对象和Json对象字符串的关系 jsonObj<->JsonString
    VS2012 MVC4 学习笔记-概览
    java中运算符的解析和计算
    Python基本数据类型之tuple
    Python基本数据类型之list
    Python基本数据类型之str
    Python基本数据类型之int
    range和xrange梳理
    python编码
    ubuntu下的ssh
  • 原文地址:https://www.cnblogs.com/momo798/p/11718639.html
Copyright © 2011-2022 走看看