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