1
votes

La fonction récursive continue de renvoyer false

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?


1 commentaires

Lorsque vous effectuez un appel récursif, vous ne retournez pas le résultat.


3 Réponses :


0
votes

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


0 commentaires

1
votes

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.


0 commentaires

1
votes

Une erreur mineure devrait être:

retourne CheckIfInKeyZone (location);


0 commentaires