javascript(+)符号串联起来而不是给出总和? [英] javascript (+) sign concatenates instead of giving sum?

查看:70
本文介绍了javascript(+)符号串联起来而不是给出总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的程序,该程序将两个数字求和. 该程序正在串联,这太令人困惑了! 有人可以帮忙吗?

I created a simple program that make the sum of two numbers BUT.. the program is concatenating instead, This is so confusing! Can anyone help?

function calculate() {
  var numberOne = document.querySelector(".first").value;
  var numberTwo = document.querySelector(".second").value;
  var sum = numberOne + numberTwo;
  document.querySelector(".result").innerHTML = "The sum of the two numbers is : " + sum;
}

<!doctype html>
<html>

<body>
  <p>Calculate sum of two numbers !</p>
  Enter 1rst Number:<br>
  <input type="number" class="first" placeholder=""><br><br> Enter 2nd Number:<br>
  <input type="number" class="second" placeholder=""><br><br>
  <input type="button" onclick="calculate()" value="calculate">
  <p class="result"></p>
</body>

</html>

推荐答案

在这里value给您一个字符串,因此是串联的.尝试将其解析为数字:

Here value gives you a string, hence the concatenation. Try parsing it as an Number instead:

var sum = parseInt(numberOne) + parseInt(numberTwo);

请参见演示小提琴 .

这篇关于javascript(+)符号串联起来而不是给出总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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