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.
You read error wrong :-) not length is undefined, but object where you try get this property - undefined.
So currentWord is undefined
because you have wrong loop condition:
i<=arrayL
,when
i == arrayL
-var currentWord = array[i]
is undefined and you get error.Just fix it:
i < arrayL
The problem is the bounds of your iteration
Note that you are going to be looking for array[array.length] doing this and that will always be undefined because the 10th item in an array of 10 items is [9], [10] is undefined.
Also, please use var here
Instead of error prone hand-written loops for iterating over an array, why not take advantage of the functions that JS provides you - in this case
Array.prototype.map
:The
Math.max.apply(this, some_array)
is the standard JS way of callingMath.max(a, b, c, d, ...)
with the given array instead of passing a list of parameters of unknown length.In ES2015 you could use the even shorter: