javascript中数字数组的总和

时间:2017-06-03 20:11:40

标签: javascript arrays reduce

在这里,我想从用户那里获取信息。拆分并将它们存储到数组中。然后显示数组的总和。

    

求和实验

<!-- for taking inputs -->
<input id="seriesInput" type="text" placeholder="please use space">
<!-- for submitting inputs -->
<input id="submiting" onclick="seriesFunction()" value="Submit" type="button">
<!-- for placing results -->
<div> Summation is <span id="sum"></span> </div>
<script type="text/javascript">

function seriesFunction()
{
    value = document.getElementById("seriesInput").value;
    // splitting string in an array
    value_arr = value.split(" ");
    alert(value_arr);
    // calling reduce method for summation
    var sum = value_arr.reduce(get_sum,0);
    // assigning result
    document.getElementById("sum").innerHTML =sum;
alert(sum);


    function get_sum(total, currentVal) {
total += currentVal;
return total;
}
}
</script>

2 个答案:

答案 0 :(得分:1)

你在get_sum函数中将currentValue作为字符串获取,尝试使用整数。你可以这样做:

function get_sum(total, currentVal) {
    currentVal = parseInt(currentVal);
    total += currentVal;
    return total;
}

答案 1 :(得分:1)

您需要将代码修改为:

function get_sum(total, currentVal) {
                total += +currentVal;
                return total;
}

+前面注意currentVal。这会将字符串转换为数字而不仅仅是int。所以好处是,如果你输入三个值,如1.1 1.2 1.3,你将得到总和为6.6。 在没有这个的情况下,你早些时候正在进行字符串连接,而不是你打算做的总和。

&#13;
&#13;
function seriesFunction() {
  value = document.getElementById("seriesInput").value;
  // splitting string in an array
  value_arr = value.split(" ");
  alert(value_arr);
  // calling reduce method for summation
  var sum = value_arr.reduce(get_sum, 0);
  // assigning result
  document.getElementById("sum").innerHTML = sum;
  alert(sum);


  function get_sum(total, currentVal) {
    total += +currentVal;
    return total;
  }
}
&#13;
<input id="seriesInput" type="text" placeholder="please use space">
<!-- for submitting inputs -->
<input id="submiting" onclick="seriesFunction()" value="Submit" type="button">
<!-- for placing results -->
<div> Summation is <span id="sum"></span> </div>
&#13;
&#13;
&#13;