简体   繁体   中英

How is maxLength able to find the longest word in the string?

Can anybody explain how maxLength is working in this section of code. How is it being used to find the longest word in the string?

function findLongestWord(str) {
  var words = str.split(' ');
  var maxLength = 0;

  for (var i = 0; i < words.length; i++) {
    if (words[i].length > maxLength) {
      maxLength = words[i].length;
    }
  }

  return maxLength;
}

findLongestWord("housework is easy when you're happy");

 function findLongestWord(str) { var words = str.split(' '); var maxLength = 0; for (var i = 0; i < words.length; i++) { if (words[i].length > maxLength) { maxLength = words[i].length; } } return maxLength; } findLongestWord("housework is easy when you're happy");

This part takes the string that is ran through the function, in this case "housework is easy when you're happy" and splits it into individual words.

var words = str.split(' ');

Once the words are split this starts at the first word and finds the length of it, since this will always be higher than the initial 0 set above the program will assume this is the longest word, in this case it's only keeping track of the longest length and not necessarily the word (this will return 9 and not housework).

Then it compares every word after to this new number, if it discovers that it's higher then it replaces the variable maxLength and sets it as the new highest number, otherwise it ignores it and goes to the next word.

  for (var i = 0; i < words.length; i++) {
    if (words[i].length > maxLength) {
      maxLength = words[i].length;
    }
  }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM