gpt4 book ai didi

javascript - 通过 obj Prop 循环的递归函数不起作用

转载 作者:行者123 更新时间:2023-11-29 18:36:49 24 4
gpt4 key购买 nike

为什么这只提醒 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));
}

最佳答案

您忘记在递归调用中添加计数。

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));
}

关于javascript - 通过 obj Prop 循环的递归函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2393778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com