【问题标题】:Return nested object with recursion - Javascript使用递归返回嵌套对象 - Javascript
【发布时间】:2020-01-26 15:20:30
【问题描述】:

我有一个带有嵌套对象的对象:

let list = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: {
        value: 4,
        next: null
      }
    }
  }
};

我需要返回list 中的所有key: value,并且我必须使用递归。我曾尝试将嵌套对象推送到函数中的局部变量,但由于名称不同,它在第二次迭代中失败了。

函数如下:

function printList(list){
  let nested = {};

  if(list.hasOwnProperty('next')) {
      nested = list.next;
      printList(nested);
  } else {
    return nested;
  }
}

有没有办法用递归解决它?

它应该返回value 属性。在这种情况下

1
2
3
4

【问题讨论】:

  • 那么在递归函数中,您实际上是在哪里打印任何内容到输出?
  • 你不应该检查对象是否有.next属性,你应该检查nested是否是null

标签: javascript object recursion


【解决方案1】:

您可以返回一个包含值的数组并在检查后获取嵌套值

function printList({ value, next }) {
    return [value, ...(next ? printList(next) : [])]
}

let list = { value: 1, next: { value: 2, next: { value: 3, next: { value: 4, next: null } } } };

console.log(printList(list));

【讨论】:

    【解决方案2】:

    您可以创建一个函数来检查是否为给定对象定义了 next,如果是,您可以将 value 以及从进一步递归调用中检索到的其余值添加到数组中:

    const list = {
      value: 1,
      next: {
        value: 2,
        next: {
          value: 3,
          next: {
            value: 4,
            next: null
          }
        }
      }
    };
    
    const get_keys = ({value, next}) => 
    	next ? [value, ...get_keys(next)] : [value];
      
    console.log(get_keys(list));

    【讨论】:

      【解决方案3】:

      这是一种尝试与您自己的尝试保持接近的方法。

      let list = {
        value: 1,
        next: {
          value: 2,
          next: {
            value: 3,
            next: {
              value: 4,
              next: null
            }
          }
        }
      };
      
      function printList(list){
        if (!list)
          return;
      
        console.log(list.value)
      
        if (list.hasOwnProperty('next'))
          printList(list.next);
      }
      
      printList(list)

      【讨论】:

      • 我已经找到了答案,我喜欢它。但无论如何,你的答案是有效的,它至少值得一票。非常感谢您的时间和精力!
      猜你喜欢
      • 2018-08-16
      • 1970-01-01
      • 2012-02-12
      • 2020-10-06
      • 2019-08-22
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多