簡體   English   中英

編譯的CoffeeScript未捕獲的TypeError

[英]Compiled CoffeeScript Uncaught TypeError

我正在嘗試將以下CoffeeScript代碼編譯為Javascript:

GetCard = ->
  do Math.floor do Math.random * 12

Results = ->
  do NewGame if prompt "You ended with a total card value of #{UserHand}. Would you like to play again?"
  else
    alert "Exiting..."

NewGame = ->
  UserHand = 0
  do UserTurn

UserTurn = ->
  while UserHand < 21
    if prompt "Would you like to draw a new card?" is "yes"
      CardDrawn = do GetCard
      UserHand += CardDrawn
      alert "You drew a #{CardDrawn} and now have a total card value of #{UserHand}."
    else
      do Results
      break

但是,如果您說是,則生成的Javascript將以下錯誤輸出到控制台:

Uncaught TypeError: number is not a function BlackJack.js:4
GetCard BlackJack.js:4
UserTurn BlackJack.js:22
NewGame BlackJack.js:14
onclick

由於某些原因,CoffeeScript也未將UserHand設置為0 我對Java相當陌生,對CoffeeScript也很陌生。 我到處搜索並閱讀了CoffeeScript文檔以及CoffeeScript Cookbook,據我所知CS代碼看起來正確,而JS卻不正確:

var GetCard, NewGame, Results, UserTurn;

GetCard = function() {
  return Math.floor(Math.random() * 12)();
};

Results = function() {
  return NewGame(prompt("You ended with a total card value of " + UserHand + ". Would you like to play again?") ? void 0 : alert("Exiting..."))();
};

NewGame = function() {
  var UserHand;
  UserHand = 0;
  return UserTurn();
};

UserTurn = function() {
  var CardDrawn, _results;
  _results = [];
  while (UserHand < 21) {
    if (prompt("Would you like to draw a new card?") === "yes") {
      CardDrawn = GetCard();
      UserHand += CardDrawn;
      _results.push(alert("You drew a " + CardDrawn + " and now have a total card value of " + UserHand + "."));
    } else {
      Results();
      break;
    }
  }
  return _results;
};

任何幫助將不勝感激。 謝謝!

更新:感謝您提供所有答案。 我只是對雙括號有些困惑,並錯誤地使用do關鍵字替換了參數括號而不是函數調用括號。 我仍然對全球范圍感到困惑。 我知道您可以在純JS中使用var關鍵字,但是在CoffeeScript文檔中,它指定您永遠不需要使用它,因為它可以為您管理范圍?

稍作閱讀后,看來您的第一個問題是因為do運算符。 據我所知,它是在循環內創建閉包以將當前值綁定到函數。 不是您這里需要的。

我不認為簡單存在任何問題:

GetCard = ->
    Math.floor( Math.random() * 12 )

第二個問題是范圍之一。 UserHand是本地NewGame ,所以它不是在訪問UserTurn (這是undefined存在)。 您可以將其設置為全局,也可以將其作為參數傳遞,但是在我看來, NewGame只需要結果:

NewGame = ->
    hand = UserTurn() // set hand to whatever the UserHand is from UserTurn

UserTurn = ->
    UserHand = 0
    while UserHand < 21
        if prompt "Would you like to draw a new card?" is "yes"
        (etc)
    UserHand // return the final UserHand value after the loop

我也建議重新考慮一些名字; 有些有點混亂。 盡管您在很多方面都進行了分解,但仍然有一些奇怪的選擇(例如,為什么UserTurn處理了21個以上的UserTurn而停止了另一個函數的處理?)

GetCard = ->
  Math.floor(Math.random() * 12)

您需要那里的括號以澄清您Math.random帶任何參數調用 Math.random 否則, functionName something表示“以某些內容作為第一個參數調用functionName”。

通常,只有當函數調用變得明顯時,才忽略對函數的調用,否則它會影響可讀性。

好:

someFunc 1, 2, 3

不清楚:

someFunc someOtherFunc someArg

(在旁邊...)

您應該查看do關鍵字。 它僅對非常特定的用途有用,並且幾乎所有的使用都是不必要/不正確的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM