循环返回奇怪的结果时的Javascript

use*_*NaN 0 javascript while-loop

如果我的代码出现问题,我会提前道歉; 我还是很陌生.

我做了一个简单的小RNG投注游戏,其中包括:

var funds = 100;
var betting = true;


function roll_dice() {
    var player = Math.floor(Math.random() * 100);
    var com = Math.floor(Math.random() * 100);
    var bet = prompt("How much do you bet? Enter a number between 1 and " + funds + " without the $ sign.");
    if (player === com) {
        alert("tie.");
    }
    else if (bet > funds) {
    alert("You don't have that much money. Please try again");
    roll_dice();
    }
    else if (player > com) {
        funds += bet;
        alert("Your roll wins by " + (player - com) + " points. You get $" + bet + " and have a total of $" + funds + ".");
    }
    else {
        funds -= bet;
        alert("Computer's roll wins by " + (com - player) + " points. You lose $" + bet + " and have a total of $" + funds + ".");
    }
}

while (betting) {
    var play = prompt("Do you wish to bet? Yes or no?");
    if (funds <= 0) {
        alert("You have run out of money.");
        betting = false;
    }
    else if (play === "yes") {
        roll_dice();
    }
    else {
        alert("Game over.");
        betting = false;
    }
}
Run Code Online (Sandbox Code Playgroud)

代码处理丢失(即减法)就好了,但似乎无法处理添加部分.如果你打赌,比如50,赢了,你最终会得到10050.除了从不寻找赌博软件程序员的工作之外,我该怎么办?

Ble*_*der 7

prompt返回一个字符串.在字符串中添加数字会产生一个字符串:

> "12" + 13
"1213"
Run Code Online (Sandbox Code Playgroud)

虽然减法会产生一个整数,但只有字符串连接是用加号完成的:

> "12" - 13
-1
Run Code Online (Sandbox Code Playgroud)

您需要将用户的输入转换为整数:

 var bet = parseInt(prompt("How much do you bet? Enter a number between 1 and " + funds + " without the $ sign."), 10);
Run Code Online (Sandbox Code Playgroud)