简单教程
提交运行
代码编辑器:
<p>点击按钮后对数组元素进行四舍五入并计算总和</p> <button onclick="myFunction()">点我</button> <p>数组元素之和: <span id="demo"></span></p> <script> var numbers = [15.5, 2.3, 1.1, 4.7]; function getSum(total, num) { return total + Math.round(num); } function myFunction(item) { document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0); } </script>
运行结果: