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.
- I've set two variables, stringArray and longestString
- I set each word in the argument to an item in an array
- I iterate through that array, writing a word length to the variable longestString if it is longer than the last.
- 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