javascript - 这个递归函数有什么问题?

标签 javascript function recursion

我正在尝试使用递归计算对象中字符串的数量,包括嵌套对象和数组中的字符串。为什么我得到 3 而不是 7;

function strCount(obj, count = 0){
  for (var key in obj) {
    if (typeof obj[key] === 'object') {
      strCount(obj[key], count);
    } else if (typeof obj[key] === 'string') {
      count++;
    }
  }
  return count;
}

var myobj = {
  first:  "1",
  second: "2",
  5: 'sd',
  third:  false,
  fourth: ["anytime",2,3,4],
  fifth:  null,
  sixth:  undefined,
  seventh:{ ana: 'hell', did: 5, boo : 'foo', har : ['kill', 5]}
};

alert(strCount(myobj));

最佳答案

不要忘记将递归调用的结果添加到count:

function strCount(obj) {
  var count = 0;
  for (var key in obj) {
    if (typeof obj[key] === 'object') {
      count += strCount(obj[key]);
    } else if (typeof obj[key] === 'string') {
      count++;
    }
  }
  return count;
}

var myobj = {first:"1",second:"2",5:'sd',third:false,fourth:["anytime",2,3,4],fifth:null,sixth:undefined,seventh:{ana:'hell',did:5,boo:'foo',har:['kill',5]}};

alert(strCount(myobj));

关于javascript - 这个递归函数有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38385933/

相关文章:

javascript - jQuery递归

javascript - 如何使用 $q 进行递归 promise

recursion - 增加浏览器中的堆栈大小

javascript - 在 React Hook 中,如何更改 useState 数组的特定值?

javascript - Node 中的箭头函数提升?

javascript - 一个函数在不同的控制台中给出不同的结果

function - "Circular"SML 函数声明

javascript - ReactJS 0.14 - 使用 promise

javascript - 错误 : EACCES: permission denied doing bower install

javascript - 如何在不使用 lambda 函数的情况下将参数发送到 React 渲染组件中的处理程序事件?