Javascript 递归函数不断返回false
我有一个小问题,为什么我的递归函数总是返回falseJavascript 递归函数不断返回false,javascript,reactjs,Javascript,Reactjs,我有一个小问题,为什么我的递归函数总是返回false const location = { name: "917", parentLocationCluster: { name: "Key Zones" ParentLocationCluster: { name: "Bla" } } } const test = CheckIfInKeyZone(location) const CheckIfInKeyZone = (pare
const location = {
name: "917",
parentLocationCluster: {
name: "Key Zones"
ParentLocationCluster: {
name: "Bla"
}
}
}
const test = CheckIfInKeyZone(location)
const CheckIfInKeyZone = (parentLocationCluster) => {
if(parentLocationCluster.name === 'Key Zones') {
return true;
}
else if(parentLocationCluster.parentLocationCluster) {
const { parentLocationCluster: location } = parentLocationCluster;
CheckIfInKeyZone(location);
}
return false;
};
点击了parentLocationCluster.name=='Key Zones',我希望返回值为true,但事实并非如此
帮助?根据Pointys的响应,结果中缺少返回的
const location = {
name: "917",
parentLocationCluster: {
name: "Key Zones"
ParentLocationCluster: {
name: "Bla"
}
}
}
const test = CheckIfInKeyZone(location)
const CheckIfInKeyZone = (parentLocationCluster) => {
if(parentLocationCluster.name === 'Key Zones') {
return true;
}
else if(parentLocationCluster.parentLocationCluster) {
const { parentLocationCluster: location } = parentLocationCluster;
return CheckIfInKeyZone(location);
}
return false;
};
您需要向递归调用添加return
const CheckIfInKeyZone = (parentLocationCluster) => {
if(parentLocationCluster.name === 'Key Zones') {
return true;
}
else if(parentLocationCluster.parentLocationCluster) {
const { parentLocationCluster: location } = parentLocationCluster;
// added return
return CheckIfInKeyZone(location);
}
return false;
};
如果不添加该返回值
,它将调用CheckIfInKeyZone
,但不会获取该返回值。小错误应该是:
返回CheckIfInKeyZone(位置)
进行递归调用时,不会返回结果。