JavaScript查找字符串最长单词的三种实现方式

作者:半夏

时间:2026-10-24

浏览:525

本文详解JavaScript中查找字符串最长单词的三种算法。通过For循环遍历比较长度、利用Sort方法排序后取首元素、以及使用Reduce方法累积最大值,分别展示具体实现逻辑与代码示例,帮助开发者掌握字符串处理与数组高阶函数的应用。

文章目录

算法挑战背景与要求

本文内容源自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;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

方法一:For循环实现

1. 使用For循环查找最长单词

该方案首先调用String.prototype.split()方法处理字符串。

  • split()方法通过指定的分隔符将字符串拆分为子串,并返回包含这些子串的数组。

在调用split()时,需在参数中传入空格字符。


var strSplit = “The quick brown fox jumped over the lazy dog”.split(‘ ‘);

正确操作后,输出结果为包含各个单词的数组:


var strSplit = [“The”, “quick”, “brown”, “fox”, “jumped”, “over”, “the”, “lazy”, “dog”];

若未在参数中指定空格,输出结果将变为包含单个字符的数组:


var strSplit = 
[“T”, “h”, “e”, “ “, “q”, “u”, “i”, “c”, “k”, “ “, “b”, “r”, “o”, “w”, “n”, “ “, “f”, “o”, “x”, “ “, “j”, “u”, “m”, “p”, “e”, “d”, “ “, “o”, “v”, “e”, “r”, “ “, “t”, “h”, “e”, “ “, “l”, “a”, “z”, “y”, “ “, “d”, “o”, “g”];

function findLongestWord(str) {
 // Step 1. Split the string into an array of strings
 var strSplit = str.split(' ');
 // var strSplit = "The quick brown fox jumped over the lazy dog".split(' ');
 // var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];
 
 // Step 2. Initiate a variable that will hold the length of the longest word
 var longestWord = 0;

 // Step 3. Create the FOR loop
 for(var i = 0; i < strSplit.length; i++){
 if(strSplit[i].length > longestWord){ // If strSplit[i].length is greater than the word it is compared with...
 longestWord = strSplit[i].length; // ...then longestWord takes this new value
  }
 }
 /* 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*/

 //Step 4. Return the longest word
 return longestWord; // 6
}

findLongestWord("The quick brown fox jumped over the lazy dog");

完整代码如下(无注释版):


function findLongestWord(str) {
 var strSplit = str.split(' ');
 var longestWord = 0;
 for(var i = 0; i < strSplit.length; i++){
 if(strSplit[i].length > longestWord){
 longestWord = strSplit[i].length;
  }
 }
 return longestWord;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

方法二:Sort排序实现

2. 使用Sort方法查找最长单词

该方案利用Array.prototype.sort()方法对数组进行排序,随后返回排序后数组第一个元素的长度。

  • sort()方法会对数组元素进行原地排序并返回该数组。

若直接对数组进行默认排序:


var sortArray = [“The”, “quick”, “brown”, “fox”, “jumped”, “over”, “the”, “lazy”, “dog”].sort();

输出结果如下:


var sortArray = [“The”, “brown”, “dog”, “fox”, “jumped”, “lazy”, “over”, “quick”, “the”];

在Unicode编码中,数字排在在大写字母之前,而大写字母排在小写字母之前。

因此,我们需要自定义排序规则。


[].sort(function(firstElement, secondElement) {  return secondElement.length — firstElement.length; })

具体做法是比较数组中第二个元素与第一个元素的长度。


function findLongestWord(str) {
 // Step 1. Split the string into an array of strings
 var strSplit = str.split(' ');
 // var strSplit = "The quick brown fox jumped over the lazy dog".split(' ');
 // var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];
 
 // Step 2. Sort the elements in the array
 var longestWord = strSplit.sort(function(a, b) { 
 return b.length - a.length;
 });
 /* Sorting process
 a   b   b.length  a.length  var longestWord
 "The"  "quick"   5   3   ["quick", "The"]
 "quick" "brown"   5   5   ["quick", "brown", "The"] 
 "brown" "fox"    3   5   ["quick", "brown", "The", "fox"]
 "fox"  "jumped"   6   3   ["jumped", quick", "brown", "The", "fox"]
 "jumped" "over"    4   6   ["jumped", quick", "brown", "over", "The", "fox"]
 "over"  "the"    3   4   ["jumped", quick", "brown", "over", "The", "fox", "the"]
 "the"  "lazy"    4   3   ["jumped", quick", "brown", "over", "lazy", "The", "fox", "the"]
 "lazy"  "dog"    3   4   ["jumped", quick", "brown", "over", "lazy", "The", "fox", "the", "dog"]
 */
 
 // Step 3. Return the length of the first element of the array
 return longestWord[0].length; // var longestWord = ["jumped", "quick", "brown", "over", "lazy", "The", "fox", "the", "dog"];
        // longestWord[0]="jumped" => jumped".length => 6
}

findLongestWord("The quick brown fox jumped over the lazy dog");

完整代码如下(无注释版):


function findLongestWord(str) {
 var longestWord = str.split(' ').sort(function(a, b) { return b.length - a.length; });
 return longestWord[0].length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

方法三:Reduce归约实现

3. 使用Reduce方法查找最长单词

该方案利用Array.prototype.reduce()方法。

  • reduce()方法接收一个回调函数,对数组的每个值(从左到右)执行该函数,最终将其归约为单个值。

reduce()会对数组中的每个元素执行一次回调函数。

可以提供一个初始值作为reduce的第二个参数,此处我们传入一个空字符串""。


[].reduce(function(previousValue, currentValue) {...}, “”);

function findLongestWord(str) {
 // Step 1. Split the string into an array of strings
 var strSplit = str.split(' ');
 // var strSplit = "The quick brown fox jumped over the lazy dog".split(' ');
 // var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];

 // Step 2. Use the reduce method
 var longestWord = strSplit.reduce(function(longest, currentWord) {
 if(currentWord.length > longest.length)
  return currentWord;
 else
  return longest;
 }, "");
 
 /* Reduce process
 currentWord  longest  currentWord.length  longest.length if(currentWord.length > longest.length)? var longestWord
 "The"    ""     3      0        yes       "The"
 "quick"   "The"    5      3        yes       "quick"
 "brown"   "quick"    5      5        no       "quick"
 "fox"    "quick"    3      5        no       "quick"
 "jumped"   "quick"    6      5        yes       "jumped"
 "over"   "jumped"   4      6        no       "jumped"
 "the"    "jumped"   3      6        no       "jumped"
 "lazy"   "jumped"   4      6        no       "jumped"
 "dog"    "jumped"   3      6        no       "jumped"
 */
 
 // Step 3. Return the length of the longestWord
 return longestWord.length; // var longestWord = "jumped" 
        // longestWord.length => "jumped".length => 6
}

findLongestWord("The quick brown fox jumped over the lazy dog");

完整代码如下(无注释版):


function findLongestWord(str) {
 var longestWord = str.split(' ').reduce(function(longest, currentWord) {
 return currentWord.length > longest.length ? currentWord : longest;
 }, "");
 return longestWord.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

以上介绍了在JavaScript中查找字符串最长单词的三种方法。更多关于JS查找字符串最长单词的内容,可参考本站往期文章或继续浏览后续相关文章,感谢支持。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章