lundi 26 août 2019

if statement won't run in for loop?

I'm working through the FreeCodeCamp basic algorithm scripting section, and I'm a bit stuck on this one.

Basically - I need to find the longest word in a sentence.

  1. I've set two variables, stringArray and longestString
  2. I set each word in the argument to an item in an array
  3. I iterate through that array, writing a word length to the variable longestString if it is longer than the last.
  4. I return the variable longestString

Why is this not working? I keep getting the error "undefined is not an object (evaluating 'longestString.length')". It seems like my if statement is not running in my for loop. Any thoughts?

Thanks in advance!

let stringArray = [];
let longestString;
function findLongestWordLength(str) {
  stringArray = str.split(' ')
  console.log(stringArray);
  for (let i = 0; i <= stringArray.length; i++){
    if (stringArray[i].length > longestString.length){
      longestString = stringArray[i].length
    }
  }
  return longestString
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");```

Aucun commentaire:

Enregistrer un commentaire