使用 JavaScript 從字串中返回長度較長的單詞。


問題

我們要求編寫一個 JavaScript 函式,輸入為一句話和一個數字。該函式應返回一個數組,其中包含長度大於該數字的所有單詞。

輸入

const str = 'this is an example of a basic sentence';
const num = 4;

輸出

const output = [ 'example', 'basic', 'sentence' ];

因為只有這三個單詞長度大於 4。

舉例

以下為程式碼 −

 即時演示

const str = 'this is an example of a basic sentence';
const num = 4;
const findLengthy = (str = '', num = 1) => {
   const strArr = str.split(' ');
   const res = [];
   for(let i = 0; i < strArr.length; i++){
      const el = strArr[i];
      if(el.length > num){
         res.push(el);
      };
   };
   return res;
};
console.log(findLengthy(str, num));

輸出

[ 'example', 'basic', 'sentence' ]

更新於: 17-Apr-2021

83 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.