Beginner here. I was doing this exercise from Coding Addict.
The exercise:
function longestWords(str){
let words = str.split(" ");
let size = 0;
let max = [''];
for(let i=0; i<words.length; i++){
if(words[i].length >= size){
size = words[i].length;
if(max[max.length-1].length <words[i].length){
max = [];
max.push(words[i]);
}
else{
max = [...max,words[i]];
}
}
}
return [...max];
}
console.log(longestWords("I woke up early today"));
console.log(longestWords("I went straight to the beach"));
Now, When I tried changing the index for max[] array to i.
if(max[i].length <words[i].length){
I got this error:
Uncaught TypeError: Cannot read property 'length' of undefined at longestWords
Can someone tell me why I can't change the index and have to use max.length-1 instead?
-
1i is used as the length of words in the loop. If i goes more than the length-1, then there won’t be an element to check. Let’s say words is 10 elements long. If you get to the second iteration of the loop and max hasn’t been added to, then you will be looking for max[1], which doesn’t exist yet. Sorry for not properly formatting, I’m on mobile.Rojo– Rojo2020年12月16日 02:56:05 +00:00Commented Dec 16, 2020 at 2:56
-
@Rojo thankyou for the explanation! appreciate it!Muzu– Muzu2020年12月16日 04:32:55 +00:00Commented Dec 16, 2020 at 4:32
2 Answers 2
When you use i, it represents the individual word in str. For example, "I woke up early today" has 5 words( or length = 5 ), but your max array has only 1 in length (which is ''). So if you use i to access max array you will get index out of bound. Unless you use the str has the same length as max.
because your max array has always one element so there is no entry in the index 1 which is max[max.length], so you better actually write it as max[0] instead.