javascript - 从 Javascript 中的用户输入中获取数组的最小值/最大值
问题描述
我对 Javascript 很陌生,需要从用户输入中找到数组的最小值和最大值,但我很难做到这一点。我试图用这个来获得最大值:
var max = Math.max.apply(Math, data);
但它没有用。
这是我到目前为止所拥有的:
var data = [];
var productInput = document.getElementById("product");
var priceInput = document.getElementById("price");
var qtyInput = document.getElementById("qty");
var messageBox = document.getElementById("display");
function insert() {
var product = productInput.value;
var price = priceInput.value;
var qty = qtyInput.value;
data.push({
product: product,
price: price,
qty: qty,
});
clearAndShow();
}
function clearAndShow() {
// Clear our fields
productInput.value = "";
priceInput.value = "";
qtyInput.value = "";
var html = "";
// Show our output html += "<tr>"; html += "<td>Product</td>";
html += "<td>price</td>";
html += "<td>quantity</td>";
html += "</tr>";
for (i = 0; i <= data.length - 1; i++) {
html += "<tr>";
html += "<td>" + data[i].product + "</td>";
html += "<td>" + data[i].price + "</td>";
html += "<td>" + data[i].qty + "</td>";
html += "</tr>";
}
messageBox.innerHTML = html;
}
<form>
<h1>Please enter data</h1>
<input id="product" type="text" placeholder="product" />
<input id="price" type="text" placeholder="price" />
<input id="qty" type="text" placeholder="qty" />
<input type="button" value="Save/Show" onclick="insert()" />
</form>
<table id="display" style="width: 100%"></table>
解决方案
正如其他人在评论中所说,Math.max适用于数字数组,而不是像您拥有的对象数组。
我建议您查看Array.prototype.reduce,它允许您通过在每个元素上运行一个函数来将数组缩减为单个值,并且可以持久访问可以在每次迭代中更改的单个值。这对于类似的过程也很有用,例如计算数组中所有数字的总和。
UsingArray.prototype.reduce
将让您将每个对象内的数字与您存储的当前最大值进行比较,并根据您的 reducer 函数返回的值保持相同的最大值或将其替换为新的最大值。您可能会发现在尝试获取最大值时用作初始值很有用-Infinity
,因此您知道它比您可能找到的任何数字都小。
所以,粗略地说,你最终会得到这样的结果:
const getMaxData = function (currentMaximum, dataEl) {
// You can examine the number inside dataEl here, and compare it to currentMaximum to decide which to return.
};
const max = data.reduce(getMaxData, -Infinity);
推荐阅读
- jira - Atlassian 帐户 ID
- python - Assign specific `QPushButton` to specific hardware button
- c - 如何在 C 中将莫尔斯编码为拉丁字母转换器
- javascript - Jquery AJAX 到纯 js
- spring - 无法使用连接到 PostgreSQL 数据库的 Spring Boot 添加和更新值
- dart - 如何在同一设备上为不同的项目使用两个版本的颤振?
- javascript - 如何基于相同的键名在枚举之间映射?
- php - 如何将数据编码为 json?
- python - 在主循环中是否有任何方法可以调试 Python tkinter 应用程序?
- ecmascript-6 - const的绝对意义是什么?