繁体   English   中英

Function 有争论并在 javascript 中创建变量

[英]Function with arguements and creating variables in javascript

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

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();

主要问题是haveDog == yes & haveDog == no 这里yesno是字符串。 所以必须比较像'haveDog === 'yes' 不使用=== 其次,仅当用户键入yes时才计算humanAge否则它将undefined

 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"); } else { alert("Thank you for you attention"); } } dogHuman();

你有几个问题,

  1. 将适当的参数传递给 function 调用。
  2. dogAge提示之后移动humanAge分配,因为这需要首先发生。
  3. 确保不要引用你的变量

 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

我不确定问题是什么,所以我将只对我注意到的所有内容进行 go :

  1. dogHuman在没有任何 arguments 的情况下被调用,并且查看您的代码,它可能不应该有任何 arguments。
  2. Javascript(事实上,大多数语言)按顺序做事,所以var humanAge = ((dogAge - 2) * 4) + 21; 应该先确定 dogAge 后的dogAge
  3. 由于haveDog正在接受prompt ,您可能希望将haveDog"yes"进行比较,而不仅仅是yes
  4. "Do you have a dog? " + "yes" + " or " + "no"可以改写为"Do you have a dog? yes or no"

变量设置一次; 每次运行它们时,它们都不会重新运行您设置的值; 这种误解很常见,这也是我认为早期humanAge定义的来源。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM