我是JavaScript的新手,并且立即面临JavaScript递归的问题。问题是,即使我将return语句放入函数的内部调用中,其值仍为undefine
d。我希望下面的示例可以解释我的问题。
// from cable是JSON,其中可能包含嵌套的内部对象 // strand是简单的整数
来自电缆样本JSON:
{
"ConnectionType":"StraightThrough",
"TotalLength":18,
"Bundles":[
{
"IsVisible":false,
"Strands":[
{
"IsGrooved":true,
"IsConnected":true,
"ConductorOrdinal":1,
"Ordinal":1,
"PrimaryColor":"#0000FF",
"Type":"Strand",
"Username":"Fiber 1",
"Description":"Fiber 1"
},
{
"IsGrooved":true,
"IsConnected":true,
"ConductorOrdinal":2,
"Ordinal":2,
"PrimaryColor":"#FFA500",
"Type":"Strand",
"Username":"Fiber 2",
"Description":"Fiber 2"
},
{
"IsGrooved":true,
"IsConnected":true,
"ConductorOrdinal":3,
"Ordinal":3,
"PrimaryColor":"#008000",
"Type":"Strand",
"Username":"Fiber 3",
"Description":"Fiber 3"
},
{
"IsGrooved":false,
"IsConnected":false,
"ConductorOrdinal":4,
"Ordinal":4,
"PrimaryColor":"#A52A2A",
"Type":"Strand",
"Username":"Fiber 4",
"Description":"Fiber 4"
}
],
"Ordinal":1,
"Type":"Bundle",
"Username":"-",
"Description":"-"
}
],
"SuperType":"Conductor",
"Fno":7200,
"Fid":51008,
"IsDefective":false,
"HasGraphics":true,
"Location":"ALBLPQ01",
"NumberOfNodes":0,
"Type":"Cable",
"Username":"Fiber Cable",
"Description":"Fiber Cable - Position - 51008"
}
代码本身:
//conductor here is undefined
//from cable is JSON that may contains nested inner objects in there
//strand is simple integer number
let conductor = FindConductor(fromCable, position.FromFeature.Strand);
//I need to check "Strands" properties because there may be conductors along with bundle
//Bundle can contains more conductors, so that's why I use recursive here
function FindConductor(item , ConductorOrdinal){
if(item.hasOwnProperty('Strands')){
item.Strands.forEach((strand)=>{
if(strand.ConductorOrdinal === ConductorOrdinal){
console.log('result!!');
console.log(strand)
return strand;
}
})
}
if(item.hasOwnProperty('Bundles')){
for (let i = 0; i < item.Bundles.length; i++) {
return FindConductor(item.Bundles[i], ConductorOrdinal);
}
}
}
问题是,对于下面提供了JSON的示例,它应返回6个匹配项。而且我可以在控制台6上看到正确的结果,但前提是我不会在递归调用之前放置 return 语句。 如果我将返回语句作为示例,则我只会收到4个而不是6个匹配项。和以前一样,函数返回null。 我是JavaScript的初学者,希望能获得明确的帮助来解释为什么会出现此问题。