【问题标题】:How to keep track of a count during recursion?如何在递归期间跟踪计数?
【发布时间】:2023-01-10 04:00:42
【问题描述】:

我正在尝试编写一个函数来计算嵌套对象中特定键的出现次数。在下面的第一个函数中,我将一个计数器初始化为参数,但它不会在函数从递归事件返回后跟踪计数。换句话说,该函数将调用自身,进入递归,正确地将计数器加 1,但是当它返回时,1 就没有了。

我是 javascript 的新手!

我最终通过使用空白数组而不是计数来解决问题;也就是我先递归收集所有嵌套对象的所有key,然后统计。所以我的问题是,为什么我可以跟踪数组,而不是计数?

//Code that does not work (keeping track of a count):

const countKeysInObj = function(obj, key, count = 0) {
    for (let prop in obj) {
        if (prop === key) {
            console.log("counting");
            count += 1;
        }
        if (typeof obj[prop] === 'object') {
            console.log("recursing");
            countKeysInObj(obj[prop], key, count);
        }
    }
    return count;
}
var testobj = { 'e': { 'x': 'y' }, 't': { 'r': { 'e': 'r' }, 'p': { 'y': 'r' } }, 'y': 'e' };
console.log(countKeysInObj(testobj, "e")) // return 1, should be 2;

【问题讨论】:

    标签: javascript recursion count return-value


    【解决方案1】:

    尝试使用返回的值并从返回的递归函数中设置计数变量。

    const countKeysInObj = function(obj, key, count = 0) {
        for (let prop in obj) {
            if (prop === key) {
                console.log("counting");
                count += 1;
            }
            if (typeof obj[prop] === 'object') {
                console.log("recursing");
                count = countKeysInObj(obj[prop], key, count); // set count here.
            }
        }
        return count;
    }
    

    【讨论】:

      【解决方案2】:

      调用堆栈为您跟踪返回值。

      考虑对键进行计数的递归定义是“当前级别的计数加上递归产生的计数”。

      const countKeysInObj = function(obj, key) {
        let count = 0;
        if (typeof obj === 'object')
          for (let prop in obj) {
            // for each key, the count is 1 if that key is the target plus the recursive result
            count += (prop === key ? 1 : 0) + countKeysInObj(obj[prop], key)
          }
        return count;
      }
      
      var testobj = { 'e': { 'x': 'y' }, 't': { 'r': { 'e': 'r' }, 'p': { 'y': 'r' } }, 'y': 'e' };
      console.log(countKeysInObj(testobj, "e")) // 2;

      【讨论】:

        猜你喜欢
        • 2021-10-10
        • 1970-01-01
        • 1970-01-01
        • 2016-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多