原文 http://www.w3cplus.com/javascript/find-the-longest-word-solution.html
找出字符串(可能是一句話)中最長的單詞並且將其長度輸出 。這個算法其實就是讓我們看看字符串中有多少個詞,每個詞有多少個字母,然后對這些詞進行比較,找出字母數最多的那個詞,並且返回這個最長字符數單詞的長度。
實現上面描述的功能,同樣先創建一個函數,比如 findLongestWord()
,並且給這個函數傳入一個 arr
參數,這個 arr
是一個包含多個詞的字符串 。然后在函數通過以下幾步來實現所需的功能:
- 先把字符串
arr
轉為數組 - 將數組中的每個元素長度轉換成一個新的數組
- 將這個數組按由小到大排序
- 取此數組中最后的數值,也就是最長的字符串
- 將這個長度值返回
JavaScript方法
在寫 findLongestWord(str)
函數實現文章開頭所述的功能,根據上面的實現思路,將會大致用到下面幾個有關於JavaScript點:
- for
- String.prototype.split()
- Array.prototype.sort()
- Array.prototype.reduce()
- Math.max()
- Array.prototype.pop()
其中 String.prototype.split()
主要是用來將字符串 str
轉換成數組 arr
。比如:
"May the force be with you".split(" "); // ["May", "the", "force", "be", "with", "you"]
這里需要注意一點,在使用 split()
方法時, ""
中間得要有一個空格( " "
),不然將會轉成這樣的一個數組:
"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"]
因為我們要做的是找出字符串 str="May the force be with you"
中最長的詞,並且將其 length
輸出來。那么我們需要的是將字符按單的 詞 而不是單獨的字母來划分。因此要特別注意代碼中 split()
的使用。
而其它幾個都是具體寫函數功能需要用的,比如 for
是用來做遍歷的,而 sort()
方法用來對數組中的元素進行排序,而且這里都將是按從小到大的升序列來排列。
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
實現方法
下面提供了幾種實現 findLongestWord(str)
的方法,不過這幾種方法簡單的可以分為 for
循環的、 sort()
和 reduce()
的。
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 }
你可以把前面的測試示例都運行一回,看看是否得到的值是正確的,如果不是,那就要檢查一下代碼是不是哪里出錯了。除了上述的方法之外,還可以 for
循環之后,通過 Math.max()
直接將數組 arrNum
中的最大值取出。如下所示:
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 }
總結
文章中通過幾種不同的方法實現了: 找出字符串(可能是一句話)中最長的單詞並且將其長度輸出 。主要使用了 for
、 sort()
和 reduce()
方法,當然在具體實現功能過程中,還運用到了JavaScript中的 split()
、 pop()
和 Math.max()
等方法。