JavaScript算法练习:找出字符串中最长的单词并输出其长度

方法1:reduce方法,max方法

1 function findLongestWord(str){
2   var strSplit = str.split(' ');
3   return strSplit.reduce(function(longest,currentWord){
4     return Math.max(longest, currentWord.length);
5 
6     },0);
7 };
8 findLongestWord("May the force be with you");//5

 

方法2: reduce方法

 1 function findLongestWord(str){
 2     var strSplit = str.split(' ');
 3     var longestWord = strSplit.reduce(function(longest,currentWord){
 5         return currentWord.length > longest.length ? currentWord : longest;
 6 
 7         },'');
 8     return longestWord.length;
11 }
12 findLongestWord("May the force be with you");

 

 

方法3:for循环

 1 function findLongestWord(str){
 2     var array = str.split(' ');
 3     var longest = 0;
 4 
 5     for(var i = 0;i < array.length;i++){
 6         if(array[i].length > longest){
 7             longest = array[i].length;
 8         }    
 9     }
10 
11     return longest;
12 } 
13 findLongestWord("May the force be with you");

来源:https://www.w3cplus.com/javascript/find-the-longest-word-solution.html

 

posted @ 2017-02-08 14:53  素雨雫晴  阅读(276)  评论(0)    收藏  举报