我正在尝试将以下 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 。我对 Javascript 相当陌生,对 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 文档中它指定您永远不需要使用它,因为它为您管理范围?