在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