tags:

views:

45

answers:

2

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));
}
+1  A: 

You forgot to add in the count on the recursive call.

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 = 0;
  for(var i in haystack) {
   if (typeof(haystack[i]) == 'object') {
    count = count + countem(needle,haystack[i]); 
   } else {
    if (needle == haystack[i]) {
     count++; 
    }
   }
  }
  return count;
 }
 alert(countem('findme',myobj));
}
Hogan
or `count += countem(needle,haystack[i]);` for the byte-savers out there.
Andy E
yep this was the solution, for some reason I had thought that count would sort've bubble up from the inner function but I think I understand why that wouldn't happen. Thanks for the help!
Karl
+1  A: 

because you reset count on every call to countem.

if (typeof(haystack[i]) == 'object') {
    count += countem(needle,haystack[i]);
}
just somebody