簡體   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