为什么这只会提醒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));
}
答案 0 :(得分:2)
您忘记在递归调用中添加计数。
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));
}
答案 1 :(得分:2)
因为您在每次调用count
时重置countem
。
if (typeof(haystack[i]) == 'object') {
count += countem(needle,haystack[i]);
}