[英]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
。 这里yes
和no
是字符串。 所以必须比较像'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();
你有几个问题,
dogAge
提示之后移动humanAge
分配,因为这需要首先发生。 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 :
dogHuman
在没有任何 arguments 的情况下被调用,并且查看您的代码,它可能不应该有任何 arguments。var humanAge = ((dogAge - 2) * 4) + 21;
应该先确定 dogAge 后的dogAge
。haveDog
正在接受prompt
,您可能希望将haveDog
与"yes"
进行比较,而不仅仅是yes
。"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.