This is my code:
function findLongestWord(str) {
var arr = str.split(" ");
var p = 0;
for (i = 0; i < arr.length; i++) {
if (arr[i].length > p){
p = arr[i].length;
}
}
return p;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
I know it works, but I am unsure why it is able to pick out only the longest word of the string. I understand that the sting gets split into an array, and the for loop checks the length of each string in the array, but how does p=arr[i].length
ALWAYS pick the longest one to return?
var arr = str.split(" ");
splits the string into an array of words.
P
holds the maximum length found so far.
We iterate though the array of words and if a word is longer then p
we assign it's length to p
At the begin p is equal to 0
for (i = 0; i < arr.length; i++) { //loop all words in array
if (arr[i].length > p){
only if p (the length of previous word) is longer than current
p = arr[i].length; //I update p with the current length (not always, but according to if statement)
So at end of loop p is equal to the length of longest word.
Well It's pretty easy : First you take the length of the first word (arr[0].length) and store the value in p.
Then you take the second one which is arr[1].length and compare it with the length of the first one which is stored in p. If the second word is bigger than the first (arr[1] > p) then p becomes array[1], etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.