Use JavaScript to find the longest word in a sentence and return its length (three methods)

Source: Internet
Author: User

Tags: sort tps string length Java Dog API returns SPL article

1. Use the Sort sorting method (the dumbest one I can remember)

functionFindlongestword (str) {varStrarr = Str.split (""); //Save the string length to an array  varLenarr = Strarr.map (function(item) {returnitem.length;    }); varLastarr = Lenarr.sort (function(A, b) {returnB-A; }); varnum = lastarr[0]; returnnum;} Findlongestword ("The quick brown fox jumped over the lazy dog");

2. Using the Math.max () method
Since the max () function can only receive numbers as arguments, here flattering uses the Apply () API to receive the attributes of the array as parameters.
Ref: 53013370

function Findlongestword (str) {  var strarr = Str.split (""// string length, save an array  var lenarr = Strarr.map (function(item) {    return  item.length;  } );     var num = Math.max.apply (null, Lenarr);     return num;} Findlongestword ("The quick brown fox jumped over the lazy dog");

3. Ways to store using temporary variables
Reference Blog: 68948891

function Findlongestword (str) {  var arr = Str.split ("");   var max = 0;   var temp;    for (var i = 0;i <arr.length;i++) {    = arr[i].length;     if (temp>max) {      = temp;    }  }   return Max;} Findlongestword ("Google do a");

Use JavaScript to find the longest word in a sentence and return its length (three methods)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: