why does this only alert 1 ?
function test() {
var myobj = {
a : '1st level prop',
b : 'findme',
c : {
aa : '2nd level prop',
bb : 'findme',
cc : {
aaa : '3rd level prop',
bbb : 'findme'
}
}
}
function countem(needle,haystack) {
var count = count || 0;
for(var i in haystack) {
if (typeof(haystack[i]) == 'object') {
countem(needle,haystack[i]);
} else {
if (needle == haystack[i]) {
count++;
}
}
}
return count;
}
alert(countem('findme',myobj));
}
You forgot to add in the count on the recursive call.