1. Use the Sort sorting method (the dumbest one I can remember)
Function findLongestWord(str) {
Var strArr = str.split(" ");
/ / Save the length of the string, save an array
Var lenArr = strArr.map(function(item){
Return item.length;
});
Var lastArr = lenArr.sort(function(a,b){
Return b-a;
});
Var num = lastArr[0];
Return num;
}
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(" ");
/ / Save the length of the string, 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++){
temp = arr[i].length; if(temp>max){
max = temp;
}
} return max;
}
findLongestWord("Google do a ");
Use JavaScript to find the longest word in a sentence and return its length (three methods)