简体   繁体   English

为什么我的递归 function 返回未定义?

[英]Why is my recursive function returning undefined?

I am working through day 7 of the Advent of Code and am stuck on why my code is returning undefined when the base case in findNestedBags hits the first condition ( data[key].includes(color) ).我正在通过代码出现的第 7 天工作,并且一直在思考为什么我的代码在findNestedBags中的基本情况达到第一个条件( data[key].includes(color) )时返回undefined It returns 0 when the second case is true so I am confused why one works and the other doesn't.当第二种情况为真时,它返回 0,所以我很困惑为什么一种有效而另一种无效。

The objective is to figure out how many different bags will lead to a bag that contains a 'shiny gold' bag.目的是弄清楚有多少不同的袋子会导致一个包含“闪亮金”袋子的袋子。 If a certain colored bag contains a shiny gold bag as an option (found in the value of key/value pair), it's an option.如果某个颜色的包包含一个 shiny 金包作为选项(在键/值对的值中找到),它是一个选项。 Alternatively, if one of the bags in list then has shiny gold as an option in its key/value pair, that can count as well...或者,如果列表中的一个包在其键/值对中具有 shiny 金作为选项,则也可以计算在内...

This is a sample of the data structure as found in the variable data , just with many more rows:这是在变量data中找到的数据结构示例,只是包含更多行:


data = {
  'vibrant violet': [ 'light gray', 'wavy aqua' ],
  'dim fuchsia': [ 'vibrant white', 'pale beige', 'shiny gold' ],
  'drab fuchsia': [ 'dotted turquoise', 'dull crimson', 'plaid violet' ],
  'dim purple': [ 'plaid silver', 'posh gray', 'plaid beige' ],
  'mirrored lavender': [ 'vibrant lime', 'vibrant violet', 'mirrored aqua', 'clear black' ],
  'posh green': []
}
let data = indexData(input);

let count = 0;
function findMatches(color, input) {
    for (let key in input) {
        
        if (input[key].includes(color)) {
            count++
        }
        else {
            let x = findNestedBags(key, color, input)
            if (x == 1) count++
        }
    }
    return count
}

function findNestedBags(key, color, data) {
    if (data[key].includes(color)) {
        return 1
    }

    else if (data[key].length == 0) {
        return 0;
    }
    else {
        data[key].forEach(item => {
            return findNestedBags(item, color, data)
        })
    }

}

forEach does not return a value. forEach不返回值。 If you want to sum all the results, you can use Array#reduce .如果要对所有结果求和,可以使用Array#reduce In addition, you can set the accumulator's initial value to 0 by passing in a second argument, so you can remove the check for the array's length being 0 .此外,您可以通过传入第二个参数将累加器的初始值设置为0 ,这样您就可以取消对数组长度是否为0的检查。

function findNestedBags(key, color, data) {
    if (data[key].includes(color)) {
        return 1
    } else {
        return data[key].reduce((acc,item) => {
            return acc + findNestedBags(item, color, data)
        }, 0)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM