javascript - 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>
解决方案
您需要先将元素值映射到数组。
数学库对从 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>
推荐阅读
- python-3.x - 使用位置和关键字参数的顺序
- jquery - 如何从其他表中获取值并在数据表中显示
- redux - React-Redux useSelector 无法传递数据
- python - 在 Python 中的类之外定义类方法
- java - Java Web Start 拒绝自签名证书
- javascript - 'self' 脚本被阻止加载,但是当我使用 nonce 时它们可以工作吗?
- python - Python 长度不匹配
- javascript - 使用 JavaScript 制作添加到收藏夹按钮
- javascript - 从右侧滚动时,图表 js 确实滚动到左侧隐藏区域
- azure-ad-b2c - Azure B2C 的 Android 示例文件也需要在 B2CConfiguration 类中复制配置文件信息