使用 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' ]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP