我有一个函数可以找到字符串中最长的单词。
function findLongestWord(str) {
var longest = str.split(' ').reduce((longestWord, currentWord) =>{
return currentWord.length > longestWord.length ? currentWord : longestWord;
}, "");
return longest;
}
console.log(findLongestWord("The quick brown fox jumped over the lazy dog"));
我很难将其转换为找到最短的单词。为什么我不能改变currentWord.length > longestWord.length
to currentWord.length < longestWord.length
?
您需要提供一个初始值reduce
函数,否则空字符串是最短的单词:
function findShortestWord(str) {
var words = str.split(' ');
var shortest = words.reduce((shortestWord, currentWord) => {
return currentWord.length < shortestWord.length ? currentWord : shortestWord;
}, words[0]);
return shortest;
}
console.log(findShortestWord("The quick brown fox jumped over the lazy dog"));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)