# JavaScript：找出字符串中最长的单词并输出其长度

• 先把字符串 arr 转为数组
• 将数组中的每个元素长度转换成一个新的数组
• 将这个数组按由小到大排序
• 取此数组中最后的数值，也就是最长的字符串
• 将这个长度值返回

## JavaScript方法

"May the force be with you".split(" ");
// ["May", "the", "force", "be", "with", "you"]


"May the force be with you".split("");
// ["M", "a", "y", " ", "t", "h", "e", " ", "f", "o", "r", "c", "e", " ", "b", "e", " ", "w", "i", "t", "h", " ", "y", "o", "u"]


reduce() 方法将数组中的每个值（从左到右）开始合并，最终返回一个值。而在这个方法中，将会调一个 callback 函数，这个函数的功能就是让我们找出数组中最大的一个值。有关于 sort() 和 reduce() 更多的介绍，可以点击这里阅读

Math.max() 方法可以很简单的从一个数组中取出最大的那个值：

Array.prototype.max = function () {
return Math.max.apply({},this);
}
var arr = [1,45,23,3,6,2,7,234,56];
arr.max(); // 234


## 测试用例

• 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

## 实现方法

### 1、for循环

function findLongestWord(str) {
// 第1步：将传给str的值"May the force be with you"转换成数组
var array = str.split(' ');

// 得到数组 ["May", "the", "force", "be", "with", "you"]
var longest = 0;

// 第2步：对数组array做遍历，并且将符合条件的值赋值给longest
for (var i = 0; i < array.length; i++) {
// array.length = 6

if (array[i].length > longest) {
// 如果为true,longest值为array[i].length;
longest = array[i].length;
}
}
/*
* array = ["May", "the", "force", "be", "with", "you"]
* array.length = 6
*
* 遍历次数  i = ?  i < array.length  i++   array[i].length  longest   array[i].length > longest   longest= array[i].length
* 1st       0     yes               1     "May".length=3      0        3 > 0 => yes                  3
* 2nd       1     yes               2     "the".length=3      3        3 > 3 => no                   3
* 3rd       2     yes               3     "force".length=5    3        5 > 3 => yes                  5
* 4th       3     yes               4     "be".length=2       5        2 > 5 => no                   5
* 5th       4     yes               5     "with".length=4     5        4 > 5 => no                   5
* 6th       5     yes               6     "you".length=3      5        3 > 5 => no                   5
* 7th       6     no
* End Loop
*/
// 第3步：输出最长词的长度
return longest; // 5
}


function findLongestWord(str) {
// 第1步：将传给str的值为："May the force be with you"转成数组
var arr = str.split(" ");

// 得到数组 arr = ["May", "the", "force", "be", "with", "you"]
var arrNum = [];

//  第2步： 对数组arr做遍历
for (var i = 0; i < arr.length; i++) { // arr.length = 6
// 将数组arr中每个元素的长度length放到一个新数组arrNum中
arrNum.push(arr[i].length);
/*
* 遍历次数  i = ?  i < arr.length  i++  arr[i]  arr[i].length  arrNum
* 1st      0      yes              1    "May"     3           [3]
* 2nd      1      yes              2    "the"     3           [3,3]
* 3rd      2      yes              3    "force"   5           [3,3,5]
* 4th      3      yes              4    "be"      2           [3,3,5,2]
* 5th      4      yes              5    "with"    4           [3,3,5,2,4]
* 6th      5      yes              6    "you"     3           [3,3,5,2,4,3]
* 7th      6      no
* End Loop
*/
}

// 第3步： 通过Math.max()取出数组arrNum中最大值，并且输出
return Math.max.apply(null, arrNum); // 5
}


### 2、sort()方法

function findLongestWord(str) {
// 第1步：将传给str的值为："May the force be with you"转成数组
var strArr = str.split(" ");
// 得到数组strArr=["May", "the", "force", "be", "with", "you"]
var numArr = [];
var sortArr = [];

// 第2步：对strArr数组做遍历，并把数组中每个词的length放到新数组numArr中
for (var i = 0; i < strArr.length; i++) {
numArr[i] = strArr[i].length;
}
// 新数组：numArr = [3,3,5,2,4,3]

// 第3步，使用sort()对数组numArr排序，由小到大
sortArr = numArr.sort(function compare(a, b) {
return a - b;
});
// 排序后的数组： sortArr = [2,3,3,3,4,5]

// 第4步：通过pop()取到数组sortArr中最后一个值，赋值给longestWord
var longestWord = sortArr.pop(); //5

// 第5步，输出longestWord
return longestWord; // 5
}


function findLongestWord(str) {
// 第1步：将传给str的值为："May the force be with you"转成数组
var arr = str.split(' ');
// 得到数组 arr = ["May", "the", "force", "be", "with", "you"]

// 第2步： 通过sort()将数组arr按由小到大排序
arr = arr.sort(function(a, b) {
return a.length - b.length;
});
/*
*     a          b     b.length   a.length      arr
*   "May"     "the"      3         3        ["May","the"]
*   "the"     "force"    5         3        ["May","the","force"]
*   "force"    "be"      2         5        ["be","May","the","force"]
*   "be"       "with"    4         2        ["be","May","the","with","force"]
*   "with"     "you"     3         4        ["be","May","the","you","with","force"]
*/
// 最长的字符排在数组最后

// 第3步：获取数组最长字符的长度
var longestString = arr.pop().length; // 5

// 第4步：返回最长字符的长度
return longestString; // 5
}


### 3、reduce()方法

function findLongestWord(str) {
// 第1步：将传给str的值为："May the force be with you"转成数组
var strSplit = str.split(' ');

// 得到数组 strSplit = ["May", "the", "force", "be", "with", "you"];

// 第2步使用reduce方法，取到strSplit数组中最长的元素
var longestWord = strSplit.reduce(function(longest, currentWord) {
return currentWord.length > longest.length ? currentWord : longest;
}, "");
// 取到最长的元素longestWord = "force"
/*
* strSplit = ["May", "the", "force", "be", "with", "you"];
* currentWord   longest   currentWord.length   longest.length   currentWord.length > longest.length  longestWord
*  "May"         ""            3                   0                  yes                               "May"
*  "the"         "May"         3                   3                  no                                "May"
*  "force"       "May"         5                   3                  yes                               "force"
*  "be"          "force"       2                   5                  no                                "force"
*  "with"        "force"       4                   5                  no                                "force"
*  "you"         "force"       3                   5                  no                                "force"
*/

// 第3步. 返回longestWord的length
return longestWord.length; // 5
// longestWord.length => "force".length => 5
}


### 4、也可以使用 reduce() 方法和 Math.max() 方法配合使用:

function findLongestWord(str) {
// 第1步：将传给str的值为："May the force be with you"转成数组
var strSplit = str.split(' ');
// 得到数组 strSplit = ["May", "the", "force", "be", "with", "you"];

// 第2步使用reduce方法，取到strSplit数组中最长的元素的length，并且返回
return strSplit.reduce(function(longest, currentWord) {
return Math.max(longest, currentWord.length)
}, 0); // "force".length = >5
}


## 总结

posted @ 2020-05-16 23:07  Tozhang  阅读(1681)  评论(0编辑  收藏  举报