在 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
广告