问题描述
我在使用parseInt函数或+操作数时遇到了一些问题。我想要输入两个数字,乘以一个第三个数字并将它们加在一起。它不是添加数字,而是将一个数字附加到另一个数字。
i'm having some trouble with the parseInt function or + operand. I want to take in two numbers, multiply one by a third number and add them together. Instead of adding the numbers it appends one number to another.
<script language = 'JavaScript'>
function calculate_total()
{
var a = 0;
var b = 0;
var t = 0;
parseInt(a = prompt('Pay 1'), 10);
//Input of 10
if(isNaN(a))
{
alert('Error A');
}
//No Error
parseInt(b = prompt('Pay 2'), 10);
//input of 12
if(isNaN(b))
{
alert('Error B');
}
//No Error
parseInt(t = (a * 20 + b), 10);
if(isNaN(t))
{
alert('Error T');
}
else
{
alert('Total Pay: ' + t);
//expected answer 212
//Actual Answer 20012
}
//No Error
}
calculate_total();
</script>
推荐答案
parseInt(a = prompt('Pay 1'), 10);
...
parseInt(b = prompt('Pay 2'), 10);
...
parseInt(t = (a * 20 + b), 10);
这里 a
, b
和 t
,所有都只有字符串数据,当它转换为int时,它立即被丢弃。所以,像这样修理它们
Here a
, b
and t
, all have got string data only and when it is converted to an int, its discarded immediately. So, fix them like this
a = parseInt(prompt('Pay 1'), 10);
...
b = parseInt(prompt('Pay 2'), 10);
...
t = a * 20 + b;
根据
因此,当您使用带有 +
运算符的字符串和数字时,结果将是两个操作数的连接。
So when you use a string and number with +
operator, result will be concatenation of both the operands.
根据
- 左边是评估MultiplicativeExpression的结果。
- 让leftValue为GetValue(左)。
- 让我们直接评估UnaryExpression。
- 设rightCalue为GetValue(右)。
- 让leftNum为ToNumber(leftValue)。
- 设rightNum为ToNumber(rightValue)。
- Let left be the result of evaluating MultiplicativeExpression.
- Let leftValue be GetValue(left).
- Let right be the result of evaluating UnaryExpression.
- Let rightValue be GetValue(right).
- Let leftNum be ToNumber(leftValue).
- Let rightNum be ToNumber(rightValue).
*
运算符基本上将两个操作数都转换为数字。所以,即使两个操作数都是字符串中的数字,结果也是正确的。
*
operator basically converts both the operands to numbers. So, the result will be proper even if both the operands are numbers in strings.
你可以用这个确认上面提到的东西
You can confirm the above mentioned things with this
var a = "100", b = "12";
console.log(a * 20); // Prints 2000, both operands are converted to numbers
console.log(a * 20 + b); // Prints 200012, as b is string, both are concatenated
这篇关于Javascript要么是parseInt,要么是+,而不是添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!