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

时间:2016-07-14 23:54:22

标签: 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));




2 个答案:

答案 0 :(得分:3)

不要忘记将递归调用的结果添加到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));




答案 1 :(得分:1)

您应该将第4行更改为count = strCount(obj[key], count);

function strCount(obj, count = 0) {
  for (var key in obj) {
    if (typeof obj[key] === 'object') {
      count = 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));