顯示陣列中最小數字的索引的 JavaScript


我們需要編寫一個 JavaScript 函式,該函式接收一個數字陣列。然後,該函式應返回陣列中最小數字的索引。

示例

以下程式碼實現上述功能 −

const arr = [3, 56, 56, 23, 7, 76, -2, 345, 45, 76, 3];
const lowestIndex = arr => {
   const creds = arr.reduce((acc, val, ind) => {
      let { num, index } = acc;
      if(val < num){
         num = val;
         index = ind;
      };
      return { num, index };
   }, {
      num: Infinity,
      index: -1
   });
   return creds.index;
};
console.log(lowestIndex(arr));

輸出

以下為在控制檯中輸出的程式碼 −

6

更新於: 2020 年 10 月 12 日

115 次觀看

開啟你的 職業

完成課程後獲得認證

立即開始
廣告