我正在尝试返回标签匹配项,但我似乎在这里做错了什么。有人可以把我推向正确的方向吗?
console.log('start');
var test = {
"ID": 234324,
"Label": "KDF",
"children": [{
"ID": 234234,
"Label": "KJDF",
"children": [{
"ID": 234324,
"Label": "KJDF"
}, {
"ID": 22323,
"Label": "LKNDF"
}, {
"ID": 34535,
"Label": "LKNSF"
}]
}, {
"ID": 323434,
"Label": "CLK"
}]
}
function testThis(thing, ID) {
if (thing.ID == ID) {
console.log('match!')
return thing.Label;
} else if (thing.children && thing.children.length) {
thing.children.forEach(function(x) {
console.log(x);
return testThis(x, ID);
})
return false;
} else {
return false;
}
}
console.log(testThis(test, 323434));
console.log('end');
最佳答案
你在哪里
thing.children.forEach(function(x) {
使用.some()
而不是 .forEach()
,像这样
return thing.children.some(function(x) {})
.forEach()
返回未定义,而 .some()
将返回 true
或 false
并且返回 true
后将停止迭代。
some()
executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such an element is found, some() immediately returnstrue
. Otherwise,some()
returnsfalse
.
关于javascript - javascript中的递归函数不返回标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36048912/