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

时间:2018-03-06 05:50:06

标签: javascript arrays ecmascript-6 reduce

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

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更改为currentWord.length < longestWord.length

3 个答案:

答案 0 :(得分:4)

您需要为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"));

答案 1 :(得分:2)

使用reduce时,initialValue是可选的,如果未提供,则您的第一个元素将用作initialValue。因此,在您的情况下,您只需要删除""

function findLongestWord(str) {
  var longest = (typeof str == 'string'? 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")); // The

答案 2 :(得分:0)

我以此方式编码

const findLongestWord = str => {
  return typeof str === 'string' 
  ? str.split(' ').reduce((sw, lw) => lw.length < sw.length ? lw :sw)
  : '';
}
console.log(findLongestWord('The quick brown fox jumps over the lazy dog.')); //'The'