Iterating an array to find the longest string. Each time I've received the error Cannot read property length of undefined
. Console.log
tells me that the length of the array as well as the length of the string are being read and understood so I cannot understand where there is an undefined property. In fact, I've just about tripled the original length of the program trying to make sure every variable is defined but still no good. Any help would be greatly appreciated.
function findLongestWord(str) {
var longest = 0;
var array = str.split(" ");
var arrayL = array.length;
for (i=0; i<=arrayL; i++) {
var currentWord = array[i];
var currentL = currentWord.length;
if (currentL > longest) {
currentL = longest;
};
};
return longest;
};
findLongestWord("The quick brown fox jumped over the lazy dog");
Edit: While the below answers did solve the issue, I also just wanted to mention for people that may later google this thread that I also had to swap my final if statement
from currentL = longest;
to longest = currentL
since longest
is what I was ultimately returning.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…