簡體   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