從 JavaScript 字串陣列中查詢最小元素


我們需要編寫一個 JavaScript 函式來接收一個字串陣列,並返回長度最短的字串的索引。

我們將簡單地使用一個 for 迴圈,並儲存長度最短的字串的索引。

因此,讓我們編寫此函式的程式碼 −

例項

其程式碼如下 −

const arr = ['this', 'can', 'be', 'some', 'random', 'sentence'];
const findSmallest = arr => {
   const creds = arr.reduce((acc, val, index) => {
      let { ind, len } = acc;
      if(val.length < len){
         len = val.length;
         ind = index;
      };
      return { ind, len };
   }, {
      ind: -1,
      len: Infinity
   });
   return arr[creds['ind']];
};
console.log(findSmallest(arr));

輸出

控制檯中的輸出如下 −

be

更新日期:2020 年 10 月 22 日

230 次瀏覽

職業生涯起航

完成課程獲得認證

開始
廣告