js怎样查找字符串的最长单词?教你几个窍门
发布时间:2022-04-07 16:21:35 所属栏目:语言 来源:互联网
导读:js如何查找字符串的最长单词?这篇文章给大家分享是关于基于Free Code Camp基本算法脚本来查找字符串的最长单词,本文会介绍三种方法,是小编比较推荐的,有需要的朋友可以看一看。 在此算法中,我们要查看每个单词并计算每个单词中有多少个字母。然后,比较
js如何查找字符串的最长单词?这篇文章给大家分享是关于基于Free Code Camp基本算法脚本来查找字符串的最长单词,本文会介绍三种方法,是小编比较推荐的,有需要的朋友可以看一看。 在此算法中,我们要查看每个单词并计算每个单词中有多少个字母。然后,比较计数以确定哪个单词的字符最多,并返回最长单词的长度。 在本文中,我将解释三种方法。首先使用FOR循环,其次使用sort()方法,第三次使用reduce()方法。 算法挑战 返回提供的句子中最长单词的长度。 您的回复应该是一个数字。 提供的测试用例 findLongestWord(“The quick brown fox jumped over the lazy dog”)返回一个数字 findLongestWord(“The quick brown fox jumped over the lazy dog”)返回6 findLongestWord(“May the force be with you”)返回5 findLongestWord(“Google do a barrel roll”)返回6 findLongestWord(“What is the average airspeed velocity of an unladen swallow”)返回8 findLongestWord(“What if we try a super-long word such as otorhinolaryngology”)返回19 function findLongestWord(str) { return str.length; /* Here strSplit.length = 9 For each iteration: i = ? i < strSplit.length? i++ if(strSplit[i].length > longestWord)? longestWord = strSplit[i].length 1st iteration: 0 yes 1 if("The".length > 0)? => if(3 > 0)? longestWord = 3 2nd iteration: 1 yes 2 if("quick".length > 3)? => if(5 > 3)? longestWord = 5 3rd iteration: 2 yes 3 if("brown".length > 5)? => if(5 > 5)? longestWord = 5 4th iteration: 3 yes 4 if("fox".length > 5)? => if(3 > 5)? longestWord = 5 5th iteration: 4 yes 5 if("jumped".length > 5)? => if(6 > 5)? longestWord = 6 6th iteration: 5 yes 6 if("over".length > 6)? => if(4 > 6)? longestWord = 6 7th iteration: 6 yes 7 if("the".length > 6)? => if(3 > 6)? longestWord = 6 8th iteration: 7 yes 8 if("lazy".length > 6)? => if(4 > 6)? longestWord = 6 9th iteration: 8 yes 9 if("dog".length > 6)? => if(3 > 6)? longestWord = 6 10th iteration: 9 no End of the FOR Loop*/ (编辑:济南站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |