Javascript递归函数返回未定义 [英] Javascript recursion function returning undefined

查看:65
本文介绍了Javascript递归函数返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我什至不确定该问题的标题是什么-我不确定到底出了什么问题.

I'm not even certain what the title of this question should be - I'm not sure what is going wrong at all.

我正在编写一个简单地遍历二叉树的函数.假设我们有一棵简单的树,例如:

I'm writing a function that simply loops through a binary tree. Let us say we have a simple tree such as:

testTree = { 
  data: 5,
  left: { 
    data: 10, 
    left: undefined, 
    right: undefined 
  },
  right: { 
    data: 2, 
    left: undefined, 
    right: undefined 
  } 
}

我们正在尝试从最左边的路径开始从中收集数据.这是向左搜索功能:

We're trying to collect the data from it, starting with going the left-most path. Here is the search left function:

function searchLeft(node, path){
  if(typeof node.left == 'undefined'){
    console.log(path);
    return path;
  }
  node = JSON.parse(JSON.stringify(node.left));
  path.push(node.data);
  searchLeft(node,path);
}

当我运行它时,内部console.log(path)显示正确的值:

When I run it, the inner console.log(path) shows the correct value:

[10]

但是如果我

console.log(searchLeft(testTree,[]));

我知道

未定义

为什么函数不能正确返回[10]?

Why isn't the function properly returning [10]?

谢谢!

推荐答案

您的递归调用必须将值返回给调用者

Your recursive call have to return the value to the caller

function searchLeft(node, path) {
    if (typeof node.left == 'undefined') {
        console.log(path);
        return path;
    }
    node = JSON.parse(JSON.stringify(node.left));
    path.push(node.data);
    return searchLeft(node, path); //here return
}

这篇关于Javascript递归函数返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆