本文介绍了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()查找字符串中最短的单词
发布评论