尝试添加号码时不能使用+ [英] cannot use + when try to add number

查看:108
本文介绍了尝试添加号码时不能使用+的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我选择选项1后,我添加数字100之后,结果如此100100

After i selected option 1 and after i add the number like 100 it results like this 100100

这是代码:

var userAmount;
    var userMoney = 100;
    var totalMoney;
    alert("1. Add");
    alert("2. Subtraction");
    var userOption = prompt("Enter your selection: ");
        if (userOption == 1) {
            userAmount = prompt("Amount: ");
            var totalMoney = userMoney + userAmount;
            alert("Total is " + totalMoney);
        }
        else {
            userAmount = prompt("Amount: ");
            var totalMoney = userMoney - userAmount;
            alert("Total is" + totalMoney);
        }


推荐答案

因为存在隐式转换当你使用 + 时。在您的情况下, + 实际上是连接值。

Because there is an implicit conversion when you are using +. In your case + is actually concatenating the values.

函数 提示 返回一个字符串,因此当您将其添加到int时,它会连接这些值。它将值作为字符串并连接值而不是添加它。

The function prompt returns a string so when you are adding it to an int it is concatenating the values. It takes both the values as string and concatenates the value instead of adding it.

MDN 说:


String运算符

除了可以在字符串
值上使用的比较运算符之外,串联运算符(+)连接两个字符串值
一起返回另一个字符串,它是两个
操作数字符串的并集。例如,my+string返回字符串my
string。

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings. For example, "my " + "string" returns the string "my string".

你需要把它投出来喜欢 Number(userAmount)类似于:

You need to cast it like Number(userAmount) Something like:

var totalMoney = userMoney + Number(userAmount);

userAmount = parseFloat(prompt("Amount: "));

因此您需要将两个值都转换为int,以便 + 运算符表现为加法而不是字符串连接。

so you need to cast both the values to an int so that + operator behaves as addition instead of string concatenation.

这篇关于尝试添加号码时不能使用+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆