查詢一個數組中(空間除外)最長的字串


我們需寫一個函式,接受一個字串字面量陣列並返回其中最長的字串的索引。在計算字串長度時,我們不必考慮空白所佔用的長度

如果兩個或兩個以上的字串有相同的最大長度,我們要返回最先這樣做的字串的索引。

我們將遍歷該陣列,按空格拆分每項,然後重新連線它們並計算長度,在此之後,我們將把它儲存在物件中。當我們遇到長度大於物件中當前儲存的長度時,我們將更新它,最後返回索引。

示例

const arr = ['Hello!', 'How are you', 'Can ', 'I use', 'splice method
with', ' strings in Js?'];
const findLongestIndex = (arr) => {
   const index = {
   '0': 0
};
const longest = arr.reduce((acc, val, index) => {
   const actualLength = val.split(" ").join("").length;
   if(actualLength > acc.length){
      return {
         index,
         length: actualLength
      };
   }
   return acc;
   }, {
      index: 0,
      length: 0
   });
   return longest.index;
};
console.log(findLongestIndex(arr));

輸出

控制檯中輸出將寫為 −

4

更新於: 20-Aug-2020

150 次檢視

開啟您的 職業生涯

完成該課程,獲得認證

立即開始學習
廣告
© . All rights reserved.