首页 > 解决方案 > math.sum 如何将一组值作为参数传递?

问题描述

我开始使用 math.js 只是为了方便,我想知道是否可以使用 math.sum 方法并将输入值的集合作为参数传递并返回所有输入值的总和,例如,像这样:

可视化我的概念的代码:

$(document).ready ( function(){
   $("#sum").val(math.sum($("#container input")))
});
input{
position:relative;
float:left;
clear:both;
text-align:center;
}
#sum{
margin-top:5px;
}
<!DOCTYPE html>
<html>
<head>
<script src=https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.3.0/math.min.js></script>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<div id="container"><input value="15"><input value="5"><input value="10"><input value="20"></div>
<input id="sum" placeholder="SUM OF ABOVE INPUTS">
</body>
</html>

标签: javascripthtmljquerymathmath.js

解决方案


您需要先将元素值映射到数组。

数学库对从 jQuery 元素集合中获取值一无所知

没有验证的简单案例:

const values = $("#container input").toArray().map(el => el.value)
$("#sum").val(math.sum(values))
input {
  position: relative;
  float: left;
  clear: both;
  text-align: center;
}

#sum {
  margin-top: 5px;
}
<!DOCTYPE html>
<html>

<head>
  <script src=https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.3.0/math.min.js></script>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>

<body>
  <div id="container"><input value="15"><input value="5"><input value="10"><input value="20"></div>
  <input id="sum" placeholder="SUM OF ABOVE INPUTS">
</body>

</html>


推荐阅读