查詢陣列中最短的字串 - 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

更新時間: 30-Sep-2020

664 次檢視

啟動你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.