Javascript将整数添加为字符串

时间:2015-07-06 10:33:10

标签: javascript html5

http://jsfiddle.net/rniemeyer/4FdcY/

例如,如果添加范围为1-2的6和4,则得到641或642而不是11或12!



function calculate()
{
  var radius1 = document.getElementById("cell1Value").value;
  var radius2 = document.getElementById("cell2Value").value;
  var radiusAvrg = (radius1 + radius2) / 2;
  var childRadius = radius1 + radius2 + (Math.floor(Math.random() * 6) + 1);
  console.log(childRadius);
  confirm("The child's radius is " + childRadius);
}

<h1>ParentCell01's Radius</h1>
<input type="text" name="cell1Value" id="cell1Value" />
<br />
<h1>ParentCell02's Radius</h1>
<input type="text" name="cell2Value" id="cell2Value"/>
<br />
<button onclick="calculate()">Calculate child's radius.</button>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

您需要将值转换为数字:

var radius1 = +document.getElementById("cell1Value").value;
var radius2 = +document.getElementById("cell2Value").value;

答案 1 :(得分:0)

在进行像

这样的数学运算之前,需要解析包含int值的字符串
var radius1 = parseInt(document.getElementById("cell1Value").value);

答案 2 :(得分:0)

这里你的功能应该是这样的。

 function calculate()
        {
            var radius1 = parseInt(document.getElementById("cell1Value").value);
            var radius2 = parseInt(document.getElementById("cell2Value").value);
            var radiusAvrg = (radius1 + radius2) / 2;
            var childRadius = radius1 + radius2 + (Math.floor(Math.random() * radiusAvrg) + 1);
            console.log(childRadius);
            confirm("The child's radius is " + childRadius);
        }