2016-07-14 97 views
1

我想計算一個對象中的字符串數量,包括使用遞歸嵌套對象和數組中的字符串。爲什麼我得到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));

+4

你調用'strCount'遞歸,但忽略它的返回值。 – Bergi

+0

如果這是你的想法,它不會增加其調用者範圍內的'count'變量。每個調用都有自己的「count」。 – Bergi

回答

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

你應該改變你的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));