在 JavaScript 中寻找字符串中的最短单词
我们需要编写一个 JavaScript 函数,该函数接收一个字符串并返回该字符串中的最短单词。
例如:如果输入字符串为 −
const str = 'This is a sample string';
则输出应为 −
const output = 'a';
示例
此代码为 −
const str = 'This is a sample string';
const findSmallest = str => {
const strArr = str.split(' ');
const creds = strArr.reduce((acc, val) => {
let { length, word } = acc;
if(val.length < length){
length = val.length;
word = val;
};
return { length, word };
}, {
length: Infinity,
word: ''
});
return creds.word;
};
console.log(findSmallest(str));输出
控制台中的输出 −
a
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP