字串中的最長單詞與最短單詞 - JavaScript


我們需要編寫一個 JavaScript 函式,該函式接收字串並返回一個包含兩個字串值的陣列,它們應該是字串中最短和最長的單詞。

例如 -

如果字串是-

const str = "Hardships often prepare ordinary people for an extraordinary destiny";

那麼輸出應該是-

const output = ["an", "extraordinary"];

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

示例

以下是程式碼 -

const str = "Hardships often prepare ordinary people for an extraordinary
destiny";
const largestSmallest = str => {
   const strArr = str.split(" ");
   let min = strArr[0];
   let max = strArr[0];
   for(let i = 1; i < strArr.length; i++){
      if(strArr[i].length < min.length){
         min = strArr[i];
      };
      if(strArr[i].length > max.length){
         max = strArr[i];
      };
   };
   return [min, max];
};
console.log(largestSmallest(str));

輸出

控制檯中的輸出:-

[ 'an', 'extraordinary' ]

更新於: 2020-09-15

936 次瀏覽

開啟你的職業

完成該課程獲得認證

開始
廣告