Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
递归-javascript_Javascript_Recursion - Fatal编程技术网

递归-javascript

递归-javascript,javascript,recursion,Javascript,Recursion,我试图用递归解决一个额外的信用问题。基本上,有一个“树”有匹配的“叶子”,我需要使用递归来检查这些匹配的叶子,如果它们匹配,则返回true,如果不匹配,则返回false 我不知道如何做到这一点,也找不到任何材料可以帮助我更好地理解递归。这是一个在线程序,学习如何编程 任何帮助都将不胜感激 Psuedo: // initialize some value // initialize some flag.. boolean // initialize some he

我试图用递归解决一个额外的信用问题。基本上,有一个“树”有匹配的“叶子”,我需要使用递归来检查这些匹配的叶子,如果它们匹配,则返回true,如果不匹配,则返回false

我不知道如何做到这一点,也找不到任何材料可以帮助我更好地理解递归。这是一个在线程序,学习如何编程

任何帮助都将不胜感激

Psuedo:

    // initialize some value
      // initialize some flag.. boolean
      // initialize some helper function and pass obj...leaf checker recursive function
        // check all the keys ...for loop/forEach
          // if a key is an object && value is undefined
            // assign value
            // return
          // if a value is an object ==> recurse
          // if a value is found and it doesn't match our initial value
          // trip our flag to false
          // return
      // return true or false

 const checkMatchingLeaves = (obj) => {

};
我的尝试:

const checkMatchingLeaves = (obj) => {
  // return true if every property on `obj` is the same
  // otherwise return false
  let  checker = Object.values(obj);
  if (Object.values(obj).length === 1) return true; 
    if (checker.map(checker[i] === checker[i + 1])) {
      i > checker.length; i++;
    }
};
这并不完全是(我认为)您想要的,但您应该能够将其用作模板,以确定要做什么:

// searchTree takes a value to try to match and an array/primitive 
// value.
function searchTree(val, node) {
  // Check if it's a value or an array. If it's a value we can
  // do the test and return, otherwise we recursively call
  // searchTree on all the children.
  // Array.some returns true if any of the function calls return
  // true. This is a shorthand for your boolean flag: it lets us
  // return early as soon as we find a match.
  return Array.isArray(node) ? 
    node.some(child => searchTree(val, child)) : // recursive call
    val === node;
}

searchTree(3, [1, 2, [8], [[[3]]]]);      // true
searchTree('abc', 'a');                   // false
searchTree('abc', ['ab', 'bc', ['abc']]); // true 

这是一个搜索实现。

递归背后的绝对基本思想是函数调用自身。查找斐波那契函数。这是递归函数的一个非常常见的例子。@FaizaHusain递归函数调用自己。假设您有一个充满子数组或原语的数组,您需要如下内容:
const searchTree=(val,tree)=>tree.some(node=>array.isArray(node)?searchTree(node):val==node)例如
搜索树(3,1,2,4,3]]
返回
true
searchTree('abc',['ab','bc',['a',['b']])
返回
false
。注意:在内部调用中应该是
searchTree(val,node)