带有争论的函数并在 javascript 中创建变量

我对编码完全陌生,我正在尝试创建一个函数来请求用户输入,将输入存储在要动态创建的变量中,最后输出变量的转换;我的代码就在下面。谢谢:


function dogHuman(yes, no) {

  var humanAge = ((dogAge - 2) * 4) + 21;

  var haveDog = prompt("Do you have a dog? " + "yes" + " or " + "no");


  if (haveDog == yes) {

    var dogAge = prompt("How old is your dog? ");

    alert("If your dog were human, it would be " + humanAge + " years old");

  } else if (haveDog == no) {

    alert("Thank you for you attention");

  } else {

    var haveDog = prompt("Do you have a dog? " + "yes" + " or " + "no" + yes + no);

  }

}


dogHuman();


POPMUISE
浏览 96回答 3
3回答

蝴蝶刀刀

主要问题是haveDog == yes& haveDog == no。这里yes&no是字符串。所以不得不比较喜欢'haveDog === 'yes'。没用===。其次humanAge,仅当用户键入时才计算,yes否则它将undefinedfunction dogHuman(yes, no) {  var haveDog = prompt("Do you have a dog? " + "yes" + " or " + "no");  if (haveDog === 'yes') {    var dogAge = prompt("How old is your dog? ");    var humanAge = ((dogAge - 2) * 4) + 21;    alert("If your dog were human, it would be " + humanAge + " years old");  } else {    alert("Thank you for you attention");  }}dogHuman();

慕丝7291255

我不确定问题是什么,所以我将回顾一下我注意到的所有内容:dogHuman在没有任何参数的情况下调用,并且查看您的代码,它可能不应该有任何参数。Javascript(事实上,大多数语言)按顺序做事,所以var humanAge = ((dogAge - 2) * 4) + 21;应该dogAge首先确定。既然haveDog是拿一个prompt,你可能想比较haveDog而"yes"不是仅仅yes。"Do you have a dog? " + "yes" + " or " + "no"可以重写为"Do you have a dog? yes or no"变量设置一次;每次运行它们时,它们都不会重新运行您设置的值;这种误解很常见,这也是我认为早期humanAge定义的来源。

largeQ

你有几个问题,将适当的参数传递给函数调用。在提示之后移动humanAge分配dogAge,因为这需要首先发生。确保不要引用你的变量function dogHuman(yes, no) {  var haveDog = prompt("Do you have a dog? " + yes + " or " + no);  if (haveDog === yes) {    var dogAge = prompt("How old is your dog? ");    var humanAge = ((dogAge - 2) * 4) + 21;    alert("If your dog were human, it would be " + humanAge + " years old");    dogHuman(yes, no); // Recursion  } else {    alert("Thank you for you attention");  }}dogHuman('yes', 'no'); // Pass your parameters into the call
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript