Home > Developer > JavaScript
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)