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

编程入门 行业动态 更新时间:2024-10-12 03:15:58
本文介绍了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()查找字符串中最短的单词

本文发布于:2023-11-30 13:14:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650109.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最短   字符串   单词   Javascript   reduce

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!