为什么2加2导致22?

use*_*722 0 html javascript

我是Javascript编码的新手,我正在尝试制作我的第一个计算器:它有三个文本框,用户在第一个文本框中输入要添加的第一个数字,第二个文本框中的第二个数字,以及然后他们点击一个按钮,添加这两个数字的结果出现在第三个文本框中.但是当我做1 + 1时它会产生11而不是2而当我做2 + 2时它会产生22而不是4.我知道这是一个非常新手的问题,但是你能帮助我吗?我究竟做错了什么?也很抱歉我的英语不好,我是巴西人.这是JS代码:

<script>
  function AddResolve() {
    document.getElementById('AddResult').value = document.getElementById('AddInputOne').value + document.getElementById('AddInputTwo').value
  }
</script>
Run Code Online (Sandbox Code Playgroud)

这是三个框和按钮的HTML代码:

<input type="text" id="AddResult">
<input type="text" id="AddInputOne">
<input type="text" id="AddInputTwo">
<input type="button" id="AddButton" onclick="AddResolve()">
Run Code Online (Sandbox Code Playgroud)

Buc*_*yle 8

这是因为Javascript中的字段值是字符串,而不是数字.你需要强制它们为整数:

document.getElementById('AddResult').value =
  parseInt(document.getElementById('AddInputOne').value) +
  parseInt(document.getElementById('AddInputTwo').value)
Run Code Online (Sandbox Code Playgroud)

parseInt()使用字段的值调用将字符串转换为整数.