我需要获取数组连接中最大值的索引。该数组用于将值输出到表中,然后我需要能够将该表中具有最大值的单元格设置为红色。这是我到目前为止所知道的:
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";如何找到连接数组中最大值的索引,并将cells[]的位置设置为它。我曾尝试使用循环和if语句来查找该值,但随后在从循环中获取该值时遇到了问题。
发布于 2017-01-05 00:26:44
您可以使用以下内容:
var largest_number = Math.max.apply(Math, my_array);
var largest_index = my_array.indexOf(largest_number);发布于 2017-01-05 00:26:40
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/
发布于 2017-01-05 00:33:28
只需将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];https://stackoverflow.com/questions/41468605
复制相似问题