在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
热门推荐
6 庆双节祝福语简短
10 职场离职文案祝福语简短
11 祝寿时祝福语简短精辟
12 生日祝福语大全女孩简短
13 祝福语简短古诗词
14 长辈钻石婚祝福语简短
15 师生聚餐的祝福语简短
16 简短送嫂子生日祝福语
17 祝福语大全简短6个
18 发廊元旦祝福语大全简短