使用 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' ]