javascript中的意外输出 [英] Unexpected output in javascript
本文介绍了javascript中的意外输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是javascript的初学者,我得到了意想不到的输出
I am beginner to javascript and i am getting unexpected output
这里是代码
<script type="text/javascript">
function add(a,b)
{
x = a+b;
return x;
}
var num1 = prompt("what is your no.");
var num2 = prompt("what is another no.")
alert(add(num1,num2));
</script>
它应该将输出作为我们在提示时输入的两个数字的总和,但它只是连接两个数字并弹出输出
it should give output as a sum of two number entered by us on prompting but it is simply concatenating the two number and popping the output
推荐答案
这是因为提示符
函数返回 String
而不是 Number
。所以你实际做的是请求2个字符串然后连接它们。如果你想将两个数字加在一起,你必须将字符串转换为数字:
This is because the prompt
function returns a String
and not a Number
. So what you're actually doing is to request 2 strings and then concatenate them. If you want to add the two numbers together you'll have to convert the strings to numbers:
var num1 = parseFloat(prompt("what is your no."));
var num2 = parseFloat(prompt("what is another no."));
或更简单:
var num1 = +prompt("what is your no.");
var num2 = +prompt("what is another no.");
这篇关于javascript中的意外输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文