繁体   English   中英

如何获取数组中最大值的索引? 的JavaScript

[英]How to get the index of the largest value in an array? JavaScript

我需要获取数组连接中最大值的索引。 该数组用于将值输出到表中,然后我需要将表中具有最大值的单元格设置为红色。 这是我到目前为止的内容:

cells[0].innerHTML = connections[0];
cells[1].innerHTML = connections[1];
cells[2].innerHTML = connections[2];
cells[3].innerHTML = connections[3];
cells[4].innerHTML = connections[4];
cells[5].innerHTML = connections[5];
cells[6].innerHTML = connections[6];
cells[7].innerHTML = connections[7];
cells[8].innerHTML = connections[8];
cells[9].innerHTML = connections[9];

cells[].style.backgroundColor = "red";

我将如何在连接数组中找到最大值的索引并为其设置cell []的位置。 我曾尝试使用循环和if语句来查找值,但随后在将该值移出循环时遇到了麻烦。

您可以使用以下内容:

var largest_number = Math.max.apply(Math, my_array);
var largest_index = my_array.indexOf(largest_number);
var maxvalue = Math.max.apply(null, connections);
var maxvalueindex = connections.indexOf(maxvalue);

参考: http : //www.jstips.co/en/calculate-the-max-min-value-from-an-array/

您只需将Math.max应用于数组即可获得最大值。 但是,如果您想要它的索引,则必须做更多的工作。

最直接的方法是执行以下操作:

connections.indexOf(Math.max.apply(Math, connections))

如果您想提高效率(因为遍历数组两次),可以编写自己的归约:

maxConnIndex = connections.reduce(function(curMax, curVal, curIdx) {
    let [maxVal, maxIdx] = curMax
    if (curVal > maxVal) {
      maxVal = curVal
      maxIdx = curIdx
    }
    return [maxVal, maxIdx]
  }, [connections[0],0])[1];

简单易行,高效的代码:

function maxIndex(array) {
  var idx, max=-Infinity;
  for (var i=array.length;i--;) {
    if (array[i]>max) {
      max = array[i];
      idx = i;
    }
  }
  return idx;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM