J'ai un peu de mal à savoir pourquoi ma fonction récursive retourne toujours false.
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;
};
Le parentLocationCluster.name === 'Key Zones' est frappé, dans lequel je m'attends à ce que la valeur de retour soit vraie, cependant, ce n'est pas le cas.
aide?
3 Réponses :
Selon la réponse de Pointys, retour manquant dans le résultat
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;
};
Vous devez ajouter return à l'appel récursif.
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;
};
Si vous n'ajoutez pas ce return , il appellera CheckIfInKeyZone , mais n'obtiendra pas la valeur de retour de cela.
Une erreur mineure devrait être:
retourne CheckIfInKeyZone (location);
Lorsque vous effectuez un appel récursif, vous ne
retournezpas le résultat.