Im getting the following error: “cannot read property ‘split’ of undefined”. However the “array” variable with the ‘split’ method attached is correctly defined in the previous code line.
function findLongestWord(str) {
for(i = 0; i < str.length; i++){
var array = str.split(" ");
array[i].split("");
}
}
findLongestWord("The quick brown fox jumped over the lazy dog");
Link to the challenge:
https://www.freecodecamp.org/challenges/find-the-longest-word-in-a-string
str.length would be way more than array length. so if your example string splits into 9 array items, when i in for loop reaches 10 array[10] will be undefined and you will get that error. basically just split string before for loop then compare i to array.length and your code should work.
function findLongestWord(str) {
var array = str.split(" ");
for(i = 0; i < array.length; i++){
array[i].split("");
}
}
1 Like
function findLongestWord(str) {
var array = str.split(" “);
array.forEach((elem)=>{
console.log(elem.split(”")) ;})
}
findLongestWord(“The quick brown fox jumped over the lazy dog”);
it should work using forEach() LOOP makes syntax a lot easier… str.split() makes String object into an array of strings , that’s why wecan use forEach there …
in your case again and again each time , your code loops through and splits the same string …and also …your array[i].split() is getting outta bound value and this value does’nt exit yet because str.length is more than array.length
2 Likes