首页 > 解决方案 > 从 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>

标签: javascriptarrays

解决方案


正如其他人在评论中所说,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);

推荐阅读