Javascript reduce() 查找字符串中最短的单词

jde*_*v99 2 javascript arrays reduce ecmascript-6

我有一个函数可以找到字符串中最长的单词。

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"));
Run Code Online (Sandbox Code Playgroud)

我很难将其转换为找到最短的单词。为什么我不能只是更改currentWord.length > longestWord.lengthcurrentWord.length < longestWord.length

31p*_*piy 5

您需要为该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"));
Run Code Online (Sandbox Code Playgroud)