[英]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.