加上等于操作员错误

时间:2014-02-15 18:19:21

标签: javascript ajax operators

您好,我试图让+ =增加余额值。我现在明白在java脚本中使用+ =是通过引用传递,但是如何使用它来传递值。

alert("Welcome to the Online Bank Teller");

        var balance = 100.00;
        var amount;
        var run = true;

        do{

            var pick = prompt("Make a selection...\n1-Check Balance, 2-Deposit, 3-Withdraw, 4-Quit");

            if(pick == 1){alert("Your balance is: $" + balance.toFixed(2));}
            else if(pick == 2){ 
                    amount = prompt("Enter the amount you want to deposit: $");

                    if(amount > 1000){alert("You can only enter up to $1000 per deposit!");}
      Right here--->balance += amount;
                    alert("Your new balance: $" + balance.toFixed(2));
            }
            else if(pick == 3){ 
                    amount = prompt("Enter the amount you want to withdraw: $");

                    if(amount > balance){alert("Amount exceeded account balance!");}
                    else if(amount > 500){alert("The max you can take out is up to $500 per withdraw!");}
                    else if (amount <= balance){
                            balance -= amount;
                            alert("Your new balance: $" + balance.toFixed(2));
                    }                               
            } 
            else if(pick == 4){run = false;}
            else{alert("Not a valid choice!");}

        }while(run)

当用户输入新存款时,如何让它改变变量内部的值。

我得到了

Your balance is: $10022

而不是

Your balance is: $122

提前致谢...

4 个答案:

答案 0 :(得分:1)

对从提示

获取的每个金额使用parseInt()函数
amount = parseInt(prompt("Enter the amount you want to deposit: $"), 10);

DEMO

答案 1 :(得分:0)

使用+=运算符向数字添加字符串会生成一个字符串。

prompt()返回一个字符串,因此您需要将返回值转换为数字:

balance += +amount;

或使用parseFloat()转换值。虽然我无法理解您是如何得到任何警报的,但由于字符串没有toFixed()方法,因此代码中的alert()应该会触发错误。

答案 2 :(得分:0)

尝试

balance = parseInt(balance) += parseInt(amount);

余额和金额是字符串,例如:

将字符串'50'添加到字符串'3'woul make'503'

将浮点值'50'添加到浮点值'3'将使'53'

答案 3 :(得分:0)

作为已经提到的parseInt函数的替代方法,有一些“快速和肮脏”的方法可以做到:

amount = 1 * prompt("Enter the amount you want to deposit: $");
// get'S converted because * is only defined on numbers

amount = +prompt("Enter the amount you want to deposit: $");
// converted because unary + is only defined on numbers

以及其他一些不常见的。