2
votes

La fonction d'invite récursive renvoie null

Je souhaite créer une fonction d'invite qui demandera jusqu'à ce que l'utilisateur saisisse une valeur, puis renvoie cette valeur.

Pourquoi ce code renvoie null lorsque j'entre en mode obligatoire, puis que je saisis une valeur ? Quelqu'un peut-il le faire fonctionner?

<!DOCTYPE html>
<html>
	<head>
		<title>Page Title</title>
	</head>
	<body>
		<button onclick="alert(UserInput('prompt with input', ''))">prompt with input</button><br/>
		<button onclick="alert(UserInput('prompt with mandantory input', '', 0))">prompt with mandantory input</button>
	</body>
</html>
function UserInput(text, defaultText, mandantory) {
  if (typeof defaultText === 'undefined')
    defaultText = '';
  if (typeof mandantory === 'undefined')
    return prompt(text, defaultText);
  else {
    var a = prompt(text, defaultText);
    if (a === '') {
      return UserInput(text, defaultText, mandantory);
    } else {
      return null;   
    }
  }
}

Remarque: il doit être appelé depuis onclick = "...".

Merci, Dejan


1 commentaires

Else renvoie un au lieu de renvoyer null dans else.


4 Réponses :


1
votes

Il renvoie null parce que vous appelez vous faites return null dans le cas où a est autre chose le '' , vous devez renvoyer a.

<!DOCTYPE html>
<html>

<head>
  <title>Page Title</title>
</head>

<body>
  <button onclick="alert(UserInput('prompt with input', ''))">prompt with input</button><br/>
  <button onclick="alert(UserInput('prompt with mandantory input', '', 0))">prompt with mandantory input</button>
</body>

</html>
function UserInput(text, defaultText, mandantory) {
  if (typeof defaultText === 'undefined')
    defaultText = '';

  var a

  do {
    // the first prompt will always be called
    a = prompt(text, defaultText)
    // repeat the loop while  a === '' and mandantory !== 'undefined'
  } while (mandantory !== 'undefined' && a === '')

  return a;
}

Mais j'utiliserais une boucle while do while au lieu d'une récursivité ici:

<!DOCTYPE html>
<html>

<head>
  <title>Page Title</title>
</head>

<body>
  <button onclick="alert(UserInput('prompt with input', ''))">prompt with input</button><br/>
  <button onclick="alert(UserInput('prompt with mandantory input', '', 0))">prompt with mandantory input</button>
</body>

</html>
function UserInput(text, defaultText, mandantory) {
  if (typeof defaultText === 'undefined')
    defaultText = '';
  if (typeof mandantory === 'undefined')
    return prompt(text, defaultText);
  else {
    var a = prompt(text, defaultText);
    if (a === '') {
      return UserInput(text, defaultText, mandantory);
    } else {
      return a;
    }
  }
}


0 commentaires

1
votes

Il renvoie null car vous le renvoyez dans votre else si une valeur est saisie. Dans votre dernier else , vous devez renvoyer a au lieu de null , lorsque a est différent de ' ':

<!DOCTYPE html>
<html>
	<head>
		<title>Page Title</title>
	</head>
	<body>
		<button onclick="alert(UserInput('prompt with input', ''))">prompt with input</button><br/>
		<button onclick="alert(UserInput('prompt with mandantory input', '', 0))">prompt with mandantory input</button>
	</body>
</html>

Remarque:

Pour vérifier si une variable est définie, vous pouvez simplement utiliser si ( obligatoire) au lieu d'écrire if (typeof mandantory === 'undefined') .

Démo:

function UserInput(text, defaultText, mandantory) {
  if (typeof defaultText === 'undefined')
    defaultText = '';
  if (mandantory)
    return prompt(text, defaultText);
  else {
    var a = prompt(text, defaultText);
    if (a === '') {
      return UserInput(text, defaultText, mandantory);
    } else {
      return a;   
    }
  }
}
if (a === '') {
  return UserInput(text, defaultText, mandantory);
} else {
  return a;   
}


0 commentaires

0
votes

Dans votre extrait:

  1. si a n'est pas nul, alors renvoie toujours null alors qu'il devrait renvoyer un
  2. pas besoin de branche else s'il y a des instructions return
  3. Vous pouvez utiliser les paramètres par défaut
  4. mandantory (typo) => n
  5. plusieurs branches retournant la même valeur doivent être évitées

vous pouvez écrire une fonction comme celle-ci:

<button id="test">Try</button>
const UserInput = async (text, defaultText = '', mandatory = false) => {
  const result = await prompt(text, defaultText);
  
  if (!result && mandatory) {
    console.log('User did not enter a correct value, try again');
    return UserInput(text, defaultText, mandatory);
  }
  
  console.log(`Returning Value: "${result}"`);
  return result;
};

document
  .getElementById('test')
  .addEventListener('click', () => UserInput('Say Something', '', true))
;


0 commentaires

0
votes

Vous pouvez faire comme ceci

​​

<!DOCTYPE html>
<html>
	<head>
		<title>Page Title</title>
	</head>
	<body>
		<button onclick="alert(UserInput('prompt with input', ''))">prompt with input</button><br/>
		<button onclick="alert(UserInput('prompt with mandantory input', '', 0))">prompt with mandantory input</button>
	</body>
</html>
function UserInput(text, defaultText, mandantory) {
  if (typeof defaultText === 'undefined')
    defaultText = '';
  if (typeof mandantory === 'undefined')
    return prompt(text, defaultText);
  else {
    var a = prompt(text, defaultText);
    if (a === '') {
      return UserInput(text, defaultText, mandantory);
    } else if (a !== null) {
      return a;   
    } else {
      return null;   
    }
  }
}


0 commentaires