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 th
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
:
function findLongestWord(s) {
return Math.max.apply(this, s.split(/\s+/).map(function(w) {
return w.length;
}));
}
The Math.max.apply(this, some_array)
is the standard JS way of calling Math.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:
function findLongestWord(s) {
return Math.max(...s.split(/\s+/).map((w) => w.length));
}
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
for (i=0; i<=arrayL; i++) {
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
for (var i=0; i < arrayL; i++) {