Javascript reduce()查找字符串中最短的单词 [英] Javascript reduce() to find the shortest word in a string

查看:71
本文介绍了Javascript reduce()查找字符串中最短的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a function that finds the longest word in a string.

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 ?

I'm having a hard time converting this to find the shortest word. Why can't I just change currentWord.length > longestWord.length to currentWord.length < longestWord.length?

推荐答案

您需要为 reduce 函数提供一个初始值,否则空白字符串是最短的单词:

You need to provide an initial value to the reduce function, otherwise a blank string is the shortest word:

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"));

这篇关于Javascript reduce()查找字符串中最短的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆